Mastering JavaScript Statements: Unlocking the Power of Control

Mastering JavaScript Statements: Unlocking the Power of Control

In the world of JavaScript, statements are the superheroes that command the browser to perform incredible feats. They pave the way for decision-making, iteration, and logic in your code, bringing it to life with precision and finesse.
Get ready to embark on an epic journey as we dive deep into the realm of JavaScript statements.

Let's look at the examples of statement we have in javascript and talk about each comprehensively one after the other with relevant examples.

  • The if Statement

  • The do-while Statement

  • The while Statement

  • The for Statement

  • The for-in Statement

  • Labeled Statements

  • The break and continue Statement

  • The with Statement

  • The switch Statement

The if Statement

The if statement is frequently used to make decisions based on conditions.

Syntax:

if (condition) {
  statement1;
} else {
  statement2;
}

The condition within the if statement can be any expression, and it is not required to result in a Boolean value upon evaluation. ECMAScript automatically converts the result of the expression into a Boolean by calling the Boolean( ) casting function on it. When the condition in the if statement evaluates to true, statement1 is executed. However, if the condition evaluates to false, statement2 is executed instead..

Let's utilize the syntax with one example to solidify our knowledge

const num = 30;
if (num > 25) {
  console.log("Greater than 25"); // Output: Greater than 25
} else {
  console.log("Less than or equal to 25");
}

The do-while Statement

The do-while statement is a post-test loop that executes the code block at least once before checking the condition.

Syntax:

do {
  statement;
} while (condition);

Before we proceed to look at some example to solidify this syntax, I would love to break down the syntax bit by bit.

  1. do: The do keyword is used to indicate the start of a do-while loop.

  2. statement: This represents the code that you want to execute repeatedly as part of the loop. It can be a single statement or a block of multiple statements enclosed in curly braces {}

  3. while: This is the loop's exit condition. A Boolean expression determines whether the loop should continue iterating or stop. The loop will continue executing the statement as long as the is true. If the condition becomes false, the loop will terminate, and the program will continue executing the code after the loop.

  4. }: This marks the end of the loop.

Now that you understand the syntax, we can proceed to look at two examples

Example 1

let result = '';
let i = 0;

do {
  i = i + 1;
  result = result + i;
} while (i < 6);

console.log(result); // Output: 123456

Let's take this first example back to mathematics to better understand how we got 123456:

i = 0, i = 0 + 1 = 1 , "" + 1 = "1" (0 < 1)
i = 1 , i = 1 + 1 = 2 , "" + 2 = "12" (1 < 5)
i = 2 , i = 2 + 1 = 3, "" + 3 = "123" (2 < 5)
i = 3, i = 3 + 1 = 4, "" + 4, = "1234" (3 < 5)
i = 4, i = 4 + 1 = 5, "" + 5 = "12345" (4 < 5)
i = 5, i = 5 + 1 = 6, "" + 5 = "123456" (5 < 6)

Example 2:

let result = "";
let i = 0;
do {
i += 1;
result += `${i} `;
} while (i > 0 && i < 6);

console.log(result); //123456

Despite ( i === 0 ) which doesn't pass the test, do block will always run the first time even if the condition we specify in while is false. That is why I chose to add the second example for you to have full grasp of do-while loop.

The while statement

The while statement is a pretest loop that executes the code block as long as the condition is true.

while (condition) {
  statement;
}
  1. while: This keyword is used to specify the beginning of a while loop.

  2. (condition): The condition is a Boolean expression that determines whether the loop should continue or stop. It is evaluated before each iteration of the loop. If the condition is true, the loop will continue iterating. If the condition is false, the loop will terminate, and the program will continue executing the code after the loop.

  3. {statement}: The statement is the code that you want to repeat as part of the loop. It can be a single statement or a block of multiple statements enclosed in curly braces {}.

let i = 0;
while (i < 10) {
  i += 2;
}
console.log(i); // Output: 10

Let me assume we don't understand how 10 is gotten?
Lets look at together to better simplify it

  1. Iteration 1: i is 0. The condition 0 < 10 is true, so the loop executes. i is increased by 2, resulting in i being 2.

  2. Iteration 2: i is 2. The condition 2 < 10 is true, so the loop executes again. i is increased by 2, resulting in i being 4.

  3. Iteration 3: i is 4. The condition 4 < 10 is true, so the loop executes once more. i is increased by 2, resulting in i being 6.

  4. Iteration 4: i is 6, The condition 6 < 10 is true, so the loop executes again. i is increased by 2, resulting in i being 8.

  5. Iteration 5: i is 8. The condition 8 < 10 is true, so the loop executes once more. i is increased by 2, resulting in i being 10.

  6. Iteration 6: i is 10. Now, the condition 10 < 10 is false because 10 is not less than 10. Therefore, the loop terminates.

The for Statement

The for statement is a pretest loop that includes initialization, condition, and post-loop expressions.

Syntax:

for (initialization; condition; post-loop-expression) {
  statement;
}

Let's further break down this syntax for us to comprehend:

  1. Initialization: This is where you declare and initialize a variable before the loop starts. It's typically used to set a starting point for the loop.

    • Example: let i = 0; initializes a variable i with a value of 0 as the starting point for the loop.
  2. Condition: This is checked before each iteration of the loop. If the condition is true, the loop continues; if it's false, the loop ends.

    • Example: i < 10; checks if the value of i is less than 10. The loop will continue to execute as long as the condition is true.
  3. Post-loop expression: This expression is evaluated at the end of each iteration, usually used to update the variable's value. It's executed after the statement(s) inside the loop have been executed.

    • Example: i++ increments the value of i by 1 after each iteration. In other words, it adds i to the current value of i.
  4. Statement: This is the code block that is executed in each iteration of the loop if the condition is true.

    • Example: console.log(i) outputs the value of i to the console in each iteration.
for (let i = 0; i < 10; i++) {
  console.log(i); // Output: 0 1 2 3 4 5 6 7 8 9
}

The for-in Statement

The for-in statement is used to iterate over the properties of an object.

Syntax:

for (variable in object) {
  statement;
}

Lets understand the syntax together to better understand how to use it.

  1. variable: This is a variable that will be assigned the property names of the object in each iteration of the loop.

    • Example: variable can be any valid variable name, such as property, key , or item.
  2. object: This is the object over which the loop will iterate. It can be any object with enumerable properties.

    • Example: object can be an object literal like {name: "Ayodele", age: 30} or a variable holding an object reference.
  3. statement: This is the code block that will be executed in each iteration of the loop. It contains the actions you want to perform on each property of the object.

Now, let us apply the syntax to see how for-in syntax works

const aboutMe = {
  fullName: "Ayoola Ayodele",
  job: "JavaScript developer",
  age: 30
};

for (const property in aboutMe) {
  console.log(`${property}`);
}

Output:

fullName
job
age

Labeled Statements

Labeled statements provide a way to specify a label for a specific statement and use it for breaking or continuing the loop.

Syntax:

label: statement;

Let us further break down the syntax to understand it before thinking about where to apply it

  1. label: It is a user-defined identifier followed by a colon ( : ). The label provides a unique name for a specific statement in your code. It allows you to refer to that statement elsewhere using the label.

    • Example: label can be any valid label name like loop1, myLabel, or start.
  2. statement: It is any valid JavaScript statement that you want to label. The statement can be a block of code, a loop, an if statement, or any other statement type.

    • Example: statement can be for (let i=0; i < 10; i++) { console.log(i) ;} or if( condition ) { statement; }.
loop1: for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break loop1;
  }
  console.log(i);
}

Output:

0
1
2

The break and continue statement

First let's address the break statement, its syntax, and an example of how it's used before we do the same for the continue statement.

i. The break statement is used to exit a loop prematurely, The break statement is a standalone and does not require any additional syntax. When executed, it immediately exits the innermost loop that encloses it.

Syntax:

break;

Example:

for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break;
  }
  console.log(i);
}

In this example, the break statement is triggered when i is equal to 3. It exits the loop immediately, and the loop terminates. The output will be:

0
1
2

ii. The continue statement allows you to bypass the remaining code within the current iteration of a loop and move on to the next iteration. It allows you to bypass the remaining code block for the current iteration and move to the next iteration of the loop.

Syntax

continue;

The continue statement is standalone and does not require any additional syntax. When executed, it immediately jumps to the next iteration of the loop. Now, let's look at a code example to see how the syntax is applied.

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(i);
}

Output:

0
1
3
4

What really happened? Why was 2 omitted from the output?

  • The condition i === 2 is true, triggering the continue statement.

  • The continue statement immediately skips the remaining code block for this iteration.

  • The loop proceeds to the next iteration without executing the console.log(i) statement.

The with statement

The with Statement (Less Commonly Used): The with statement sets the scope of code within a specific object, allowing access to its properties and methods.

Syntax:

with (expression) {
  statement;
}

Let's break down the syntax comprehensively;

expression: It represents any valid JavaScript expression that evaluates to an object. The with statement sets the scope of the code block to the properties and methods of that object.

statement: It is the code block that will be executed within the scope of the object specified in the with statement. The code block can contain any valid JavaScript statements.

Now that you understand the syntax, let's see its application.

const person = {
  name: "Ayodele",
  age: 30,
};

with (person) {
  console.log(name); // Output: Ayodele
  console.log(age); // Output: 30
}

In this example, the with statement sets the scope of the code block to the properties and methods of the person object. Inside the code block, the name and age properties can be accessed directly without referencing person.name and person.age.

The output of this code will be

Ayodele
30

However, it's important to note that the with statement is less commonly used in modern javascript because it can have performance implications, affect code readability, and is not compatible with strict mode. As a result of these setbacks , it is advisable not to use with statement but instead use javascript features like destructuring or function parameters to access object properties and methods.

The switch statement

The switch statement is used to compare a variable against multiple values and execute different code blocks based on the match.

Syntax:

switch (expression) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
  default:
    statement;
}
  1. expression: It represents any valid JavaScript expression that you want to evaluate and compare against the cases. The value of this expression is used to determine which case to execute.

    • Example: expression can be a variable, a function call, or a literal value.
  2. case value1, case value2: These are the individual cases that are compared against the value of the expression. If a case matches the value of the expression, the corresponding statements are executed.

    • Example: value1 and value2 can be any valid value that you want to compare against the expression. For example, they can be strings, numbers, or variables.
  3. statement1, statement2: These are the statements that are executed if their corresponding case matches the value of the expression.

    • Example: statement1 and statement2 can be any valid JavaScript statements or a code block enclosed within curly braces { }.
  4. break: The break keyword is used to exit the switch statement once a case is matched and executed. It prevents the execution from falling through to the next case.

    • Example: After executing a case and encountering a break statement, the program will exit the switch statement.
  5. default: This is an optional case that is executed when none of the other cases match the value of the expression. It acts as a fallback case when no other cases are satisfied.

    • Example: If none of the cases match the expression, the default case's statements will be executed.

Before we look at the application of this syntax. I will give an example without the use of a switch statement and the same example with the use of switch statement. Lets go!

Example 1: without switch statement

const dayNumber = 3;
let dayOfWeek;

if (dayNumber === 1) {
  dayOfWeek = "Sunday";
} else if (dayNumber === 2) {
  dayOfWeek = "Monday";
} else if (dayNumber === 3) {
  dayOfWeek = "Tuesday";
} else if (dayNumber === 4) {
  dayOfWeek = "Wednesday";
} else if (dayNumber === 5) {
  dayOfWeek = "Thursday";
} else if (dayNumber === 6) {
  dayOfWeek = "Friday";
} else if (dayNumber === 7) {
  dayOfWeek = "Saturday";
} else {
  dayOfWeek = "Invalid day";
}

console.log("The day of the week is: " + dayOfWeek); // Output: The day of the week is: Tuesday

In this example, we have a dayNumber variable representing the numeric day (e.g., 1 for Sunday, 2 for Monday, etc.). We use a series of if...else if statements to compare the value of dayNumber with each possible day and assign the corresponding dayOfWeek string

Example 2: with switch statement

const dayNumber = 3;
let dayOfWeek;

switch (dayNumber) {
  case 1:
    dayOfWeek = "Sunday";
    break;
  case 2:
    dayOfWeek = "Monday";
    break;
  case 3:
    dayOfWeek = "Tuesday";
    break;
  case 4:
    dayOfWeek = "Wednesday";
    break;
  case 5:
    dayOfWeek = "Thursday";
    break;
  case 6:
    dayOfWeek = "Friday";
    break;
  case 7:
    dayOfWeek = "Saturday";
    break;
  default:
    dayOfWeek = "Invalid day";
}

console.log("The day of the week is: " + dayOfWeek); // Output: The day of the week is: Tuesday

In this example, we use the switch statement to evaluate the value of dayNumber and execute the corresponding case. The break statement is used after each case to exit the switch statement. If none of the cases match, the default case assigns the dayOfWeek as "Invalid day".

Both examples achieve the same result, but the switch statement provides a more concise and readable way to handle multiple cases based on the value of an expression.

Conclusion

In conclusion, JavaScript statements are fundamental building blocks that allow us to control the flow of our code and make decisions. We explored various types of statements, including the if, do-while, while, for, for-in, labeled, break, continue, with, and switch statements.

The if statement helps us execute code based on a specific condition, while the do-while and while statements allow us to repeatedly execute code as long as a condition is true. The for statement provides a compact way to iterate over a block of code for a specific number of times, and the for-in statement is used to iterate over the properties of an object.

We learned about labeled statements, which enable us to break or continue loops using custom labels. The break statement allows us to exit a loop prematurely, while the continue statement allows us to skip the current iteration and move to the next.

We briefly discussed the less commonly used with statement, which sets the scope of code within a specific object, and the versatile switch statement, which compares a variable against multiple values and executes different code blocks based on the match.

By understanding and utilizing these statements, you have gained powerful tools to create dynamic and flexible JavaScript code. Keep practicing and experimenting with these statements to enhance your programming skills and build amazing applications.

Please watch out for my next articles in the Javascript roadmap I have provided. Happy coding!