Control Flow in JavaScript

Control Flow in JavaScript

Welcome to Day 4 of our 30-day JavaScript and Node.js learning series! In the last article, we introduced you to the basics of JavaScript syntax. Today, we’ll dive deeper into one of the most crucial topic—control flow in JavaScript.

Introduction to Control Flow

Control flow refers to the order in which statements are executed in a JavaScript program. By default, JavaScript code is executed from top to bottom line by line. This can be changed using control flow.

It allows you to make decisions and execute code conditionally or repeatedly based on certain conditions.

By understanding control flow, you can create more dynamic and flexible applications.

Types of Control flow statements

  • Conditional Statements – These statements are used for decision making. This basically check whether a certain condition is satisfied or not, then decides which code need to be executed.
    • If Statements
    • Switch
    • Ternary
  • Iterative Statements – This statement executes the code repeatedly until a certain condition is met. Loops allows us to perform repetitive tasks with less code.
    • For loop
    • do/while loop
    • for…in
    • for…of

General Control Flow Graphs

Conditional Statements

Control flow graph for if statement

If Statement

Control flow graph for if-else statement

If-else Statement

Control flow graph for if-else-if statement

If-else-if Statement

Control flow graph for switch case statement

Switch case Statement

Iterative Statements

Control flow graph of for loop

For loop

Control flow graph of while loop

While loop

Control flow graph of do-while loop

Do-while loop

Get all the control flow graph downloaded below.

If Statements

If statements are the most basic form of control flow in JavaScript. They allow you to execute a block of code only if a certain condition is true. The syntax for an if statement is as follows:

if (condition) {
  // Code to be executed if the condition is true
}

Here’s an example of using an if statement:

let age = 18;

if (age >= 18) {
  console.log("You are eligible to vote.");
}

In this example, the code inside the if block will only be executed if the value of age is greater than or equal to 18.

Else and Else If Statements

You can use else and else if clauses to provide alternative actions based on different conditions. The else clause is executed if the if condition is false. The else if clause allows you to check additional conditions before executing the else clause.

Here’s an example of using else and else if statements:

let grade = 85;

if (grade >= 90) {
  console.log("Excellent!");
} else if (grade >= 80) {
  console.log("Good job!");
} else {
  console.log("Needs improvement.");
}

In this example, the code will output “Excellent!” if grade is greater than or equal to 90, “Good job!” if grade is greater than or equal to 80, and “Needs improvement.” otherwise.

Switch Statements

Switch statements provide a more concise way to compare a value against multiple cases. The syntax for a switch statement is as follows:

switch (expression) {
  case value1:
    // Code to be executed if expression equals value1
    break;
  case value2:
    // Code to be executed if expression equals value2
    break;
  // ...
  default:
    // Code to be executed if no case matches
}

Here’s an example of using a switch statement:

let dayOfWeek = "Wednesday";

switch (dayOfWeek) {
  case "Monday":
    console.log("It's a workday.");
    break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("It's a weekday.");
    break;
  case "Saturday":
  case "Sunday":
    console.log("It's the weekend!");
    break;
  default:
    console.log("Invalid day.");
}

In this example, the switch statement compares the value of dayOfWeek against different cases and executes the corresponding code. The break statement is used to exit the switch statement once a matching case is found.

For Loops

For loops are used to execute a block of code a specified number of times. They are often used to iterate over arrays or perform repetitive tasks. The syntax for a for loop is as follows:

for (initialization; condition; increment/decrement) {
  // Code to be executed
}

Here’s an example of using a for loop to iterate over an array:

let numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

In this example, the for loop iterates over each element in the numbers array and logs it to the console.

Other than the general for loop, JavaScript has other two for loop; for…in and for…of.

  • for…in – iterates over all enumerable property keys of an object.
  • for…of – iterates over the values of an iteratable object.

While and Do…While Loops

These are used for indefinite iteration. While loops continue to execute as long as a specified condition is true. Do…while loops execute at least once, even if the condition is false initially.

Here’s an example of using a while loop:

let count = 0;

while (count < 5) {
  console.log("Count:", count);
  count++;
}

In this example, the while loop continues to execute as long as count is less than 5.

Here’s an example of using a do…while loop:

let input;

do {
  input = prompt("Enter a number:");
} while (isNaN(input));

console.log("You entered:", input);

In this example, the do…while loop prompts the user for a number until the user enters a valid number.

Break and Continue Statements

The break statement is used to exit a loop prematurely. The continue statement is used to skip the current iteration of a loop and proceed to the next iteration.   

Here’s an example of using break to exit a loop:   

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

In this example, the loop will break when i reaches 5.

Here’s an example of using continue to skip an iteration:

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

In this example, the loop will skip the iteration where i is 3.

Additional Tips

  • Nested conditions and loops: You can nest if statements, switch statements, and loops within each other to create more complex control flow structures.
  • Logical operators and comparison operators: These operators allow you to combine conditions and compare values.
  • Ternary operator: The ternary operator provides a concise way to write conditional expressions.
  • Code blocks and indentation: Use code blocks and proper indentation to improve readability and maintainability of your code.

Summary

Control flow is a fundamental concept in JavaScript that determines the order in which statements are executed. It allows you to make decisions and execute code conditionally or repeatedly based on certain conditions.

Key control flow structures in JavaScript include:

  • If statements: Used to execute code conditionally based on a condition.
  • Else and Else If statements: Provide alternative actions based on different conditions.
  • Switch statements: Compare a value against multiple cases and execute the corresponding code.
  • For loops: Used to execute a block of code a specified number of times.
  • While and Do…While loops: Used for indefinite iteration.
  • Break and Continue statements: Used to control the execution of loops.

By understanding and effectively using control flow structures, you can create more dynamic, efficient, and flexible JavaScript applications.

Conclusion

Understanding control flow is essential for writing effective and dynamic JavaScript code. By using if statements, switch statements, loops, and break/continue statements, you can make decisions, execute code conditionally, and iterate over data. In the next article, we’ll explore JavaScript Functions, taking your understanding to the next level!



Share the lessons with your friends


2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *