JavaScript Control Flow: A Complete Guide for Beginners

One of the most important concepts in JavaScript is control flow, which is the order in which the computer executes statements in a script. Control flow determines how your program behaves and responds to different situations and inputs. In this article, I will explain how to control the flow of execution in JavaScript, using conditional statements (if, else, switch) and looping statements (for, while, do-while, for-in, for-of, break, continue). I will also provide some examples and code snippets to help you understand and practice these concepts.

Conditional statements

A conditional statement is a set of commands that executes if a specified condition is true. Conditional statements allow you to make decisions based on the value of a variable, the result of a comparison, or the state of a logical expression. JavaScript supports two types of conditional statements: if...else and switch.

i.) if...else statement

The if...else statement is the most basic and common type of conditional statement. It has the following syntax:

Javascript
                        
if (condition) {
  // Statements to execute if condition is true
} else {
  // Statements to execute if condition is false
}

Here, the condition can be any expression that evaluates to true or false. If the condition evaluates to true, the statements inside the first block are executed. Otherwise, the statements inside the second block are executed. You can use any type of statement inside the blocks, including further nested if statements.

You can also use the else if clause to test multiple conditions in sequence, as follows:

Javascript
                        
if (condition1) {
  // Statements to execute if condition1 is true
} else if (condition2) {
  // Statements to execute if condition2 is true
} else if (conditionN) {
  // Statements to execute if conditionN is true
} else {
  // Statements to execute if none of the conditions are true
}

In this case, only the first block whose condition evaluates to true will be executed. If none of the conditions are true, the last block will be executed.

Here is an example of using the if...else statement to check the age of a user and display a different message depending on the age range:

Javascript
                        
let age = prompt("How old are you?"); // Ask the user for their age
if (age < 18) {
  // If the age is less than 18
  alert("You are too young to enter this site."); // Display this message
} else if (age >= 18 && age < 21) {
  // If the age is between 18 and 21
  alert("You can enter this site, but you cannot drink alcohol."); // Display this message
} else {
  // If the age is 21 or more
  alert("You can enter this site and drink alcohol."); // Display this message
}

ii.) switch statement

The switch statement is another type of conditional statement that can be used to execute different blocks of code based on the value of a variable or expression. The switch statement has the following syntax:

Javascript
                        
switch (expression) {
  case value1:
    // Statements to execute if expression matches value1
    break;
  case value2:
    // Statements to execute if expression matches value2
    break;
  // ...
  case valueN:
    // Statements to execute if expression matches valueN
    break;
  default:
    // Statements to execute if expression doesn't match any value
    break;
}

Here, the expression can be any value or expression that can be compared with the case values. The case values can be any constant or literal value. The break statement is used to terminate the execution of the current case and exit the switch statement. The default clause is optional and is used to provide a default action if none of the case values match the expression.

The switch statement works by comparing the expression with each case value using the strict equality operator (===). If a match is found, the statements associated with that case are executed. If no match is found, the statements associated with the default clause are executed (if present).

Here is an example of using the switch statement to display a different message based on the day of the week:

Javascript
                        
let day = new Date().getDay(); // Get the current day of the week (0-6)
switch (day) {
  case 0:
    // If the day is 0 (Sunday)
    alert("It's Sunday, enjoy your weekend!"); // Display this message
    break;
  case 1:
    // If the day is 1 (Monday)
    alert("It's Monday, back to work!"); // Display this message
    break;
  case 2:
    // If the day is 2 (Tuesday)
    alert("It's Tuesday, have a great day!"); // Display this message
  break;
  case 3:
    // If the day is 3 (Wednesday)
    alert("It's Wednesday, halfway there!"); // Display this message
    break;
  case 4:
    // If the day is 4 (Thursday)
    alert("It's Thursday, almost there!"); // Display this message
    break;
  case 5:
    // If the day is 5 (Friday)
    alert("It's Friday, the weekend is here!"); // Display this message
    break;
  case 6:
    // If the day is 6 (Saturday)
    alert("It's Saturday, enjoy your weekend!"); // Display this message
    break;
  default:
    // If the day is not a valid value
    alert("Invalid day!"); // Display this message
    break;
}

Looping statements

A looping statement is a set of commands that executes repeatedly until a specified condition is false. Looping statements allow you to perform repetitive tasks with less code and more efficiency. JavaScript supports several types of looping statements: for, while, do-while, for-in, for-of, break, and continue.

i.) for statement

The for statement is the most common type of looping statement. It has the following syntax:

Javascript
                        
for (initialization; condition; final-expression) {
  // Statements to execute on each iteration
}

Here, the initialization is an expression that is executed once before the loop starts. It is usually used to declare and initialize a loop counter variable. The condition is an expression that is evaluated before each iteration. If the condition evaluates to true, the statements inside the loop are executed. If the condition evaluates to false, the loop terminates. The final-expression is an expression that is executed at the end of each iteration. It is usually used to increment or decrement the loop counter variable.

Here is an example of using the for statement to display the numbers from 1 to 10:

Javascript
                        
for (let i = 1; i <= 10; i++) {
  // Declare and initialize i to 1; check if i is less than or equal to 10; increment i by 1
  console.log(i); // Display the value of i
}

ii. while statement

The while statement is another type of looping statement that executes a block of code as long as a specified condition is true. It has the following syntax:

Javascript
                        
while (condition) {
  // Statements to execute while condition is true
}

Here, the condition can be any expression that evaluates to true or false. The statements inside the loop are executed repeatedly until the condition evaluates to false. The condition is checked before each iteration, so it is possible that the loop never executes if the condition is initially false.

Here is an example of using the while statement to display the numbers from 1 to 10:

Javascript
                        
let i = 1; // Declare and initialize i to 1
while (i <= 10) {
  // Check if i is less than or equal to 10
  console.log(i); // Display the value of i
  i++; // Increment i by 1
}

iii.) do-while statement

The do-while statement is a variation of the while statement that executes a block of code once and then repeats it as long as a specified condition is true. It has the following syntax:

Javascript
                        
do {
  // Statements to execute once and then repeat while condition is true
} while (condition);

Here, the condition can be any expression that evaluates to true or false. The statements inside the loop are executed at least once, regardless of the initial value of the condition. The condition is checked after each iteration, so the loop will continue until the condition evaluates to false.

Here is an example of using the do-while statement to display the numbers from 1 to 10:

Javascript
                        
let i = 1; // Declare and initialize i to 1
do {
  // Execute this block at least once
  console.log(i); // Display the value of i
  i++; // Increment i by 1
} while (i <= 10); // Check if i is less than or equal to 10

iv.) for-in statement

The for-in statement is a type of looping statement that iterates over the enumerable properties of an object. It has the following syntax:

Javascript
                        
for (variable in object) {
  // Statements to execute for each property
}

Here, the variable is a name that will hold the name of each property on each iteration. The object is an object whose properties will be iterated over. The statements inside the loop are executed for each property of the object.

Here is an example of using the for-in statement to display the properties and values of an object:

Javascript
                        
let person = {name: "Alice", age: 25, occupation: "programmer"}; // Declare and initialize an object
for (let prop in person) {
  // Iterate over the properties of the object
  console.log(prop + ": " + person[prop]); // Display the property name and value
}

This will output:

Javascript
                        
name: Alice
age: 25
occupation: programmer

Note: The for-in statement does not guarantee the order of iteration, and it may also iterate over inherited or non-enumerable properties. To avoid this, you can use the hasOwnProperty() method or the Object.keys() function to filter the properties.

v.) for-of statement

The for-of statement is a type of looping statement that iterates over the values of an iterable object, such as an array, a string, a map, or a set. It has the following syntax:

Javascript
                        
for (variable of object) {
  // Statements to execute for each value
}

Here, the variable is a name that will hold the value of each element on each iteration. The object is an iterable object whose values will be iterated over. The statements inside the loop are executed for each value of the object.

Here is an example of using the for-of statement to display the elements of an array:

Javascript
                        
let colors = ["red", "green", "blue"]; // Declare and initialize an array
for (let color of colors) {
  // Iterate over the values of the array
  console.log(color); // Display the value
}

This will output:

Javascript
                        
red
green
blue

Note: The for-of statement works only with iterable objects, not with regular objects. To iterate over the properties of an object, use the for-in statement.

vi.) break statement

The break statement is used to terminate the execution of a loop or a switch statement and transfer control to the next statement after the loop or switch. It has the following syntax:

Javascript
                        
break;

You can also use an optional label to identify which loop or switch to break out of, as follows:

Javascript
                        
break label;

Here, label is a name that identifies a loop or a switch statement.

Here is an example of using the break statement to exit a loop when a certain condition is met:

Javascript
                        
let sum = 0; // Declare and initialize a variable to hold the sum
for (let i = 1; i <= 100; i++) {
  // Iterate from 1 to 100
  sum += i; // Add i to the sum
  if (sum > 1000) {
    // If the sum exceeds 1000
    break; // Exit the loop
  }
}
console.log(sum); // Display the sum

This will output:

Javascript
                        
1035

Here is an example of using the break statement with a label to exit a nested loop:

Javascript
                        
outer: // Label the outer loop
for (let i = 0; i < 3; i++) {
  // Iterate from 0 to 2
  console.log("Outer loop: " + i); // Display the outer loop counter
  inner: // Label the inner loop
  for (let j = 0; j < 3; j++) {
    // Iterate from 0 to 2
    console.log("Inner loop: " + j); // Display the inner loop counter
    if (j === 1) {
      // If the inner loop counter is 1
      break outer; // Exit the outer loop
    }
  }
}

This will output:

Javascript
                        
Outer loop: 0
Inner loop: 0
Inner loop: 1

vii.) continue statement

The continue statement is used to skip the current iteration of a loop and continue with the next one. It has the following syntax:

Javascript
                        
continue;

You can also use an optional label to identify which loop to continue, as follows:

Javascript
                        
continue label;

Here, label is a name that identifies a loop.

Here is an example of using the continue statement to skip even numbers in a loop:

Javascript
                        
for (let i = 1; i <= 10; i++) {
  // Iterate from 1 to 10
  if (i % 2 === 0) {
    // If i is divisible by 2
    continue; // Skip this iteration
  }
  console.log(i); // Display the odd number
}

This will output:

Javascript
                        
1
3
5
7
9

Here is an example of using the continue statement with a label to skip an iteration of a nested loop:

Javascript
                        
outer: // Label the outer loop
for (let i = 0; i < 3; i++) {
  // Iterate from 0 to 2
  console.log("Outer loop: " + i); // Display the outer loop counter
  inner: // Label the inner loop
  for (let j = 0; j < 3; j++) {
    // Iterate from 0 to 2
    if (j === 1) {
      // If the inner loop counter is 1
      continue outer; // Skip this iteration of the outer loop
    }
    console.log("Inner loop: " + j); // Display the inner loop counter
  }
}

This will output:

Javascript
                        
Outer loop: 0
Inner loop: 0
Outer loop: 1
Inner loop: 0
Outer loop: 2
Inner loop: 0

Conclusion

In this article, you learned about the control flow in JavaScript and how to use different types of statements to control the order and logic of your code. You learned how to use conditional statements (if...else and switch) to execute different blocks of code based on the value of a variable or expression. You also learned how to use looping statements (for, while, do-while, for-in, for-of, break, and continue) to execute a block of code repeatedly until a specified condition is false or to skip or terminate a loop iteration. You also saw some examples and code snippets to demonstrate how these statements work and how to use them with variables, data types, and logic.