Control Flow Statements

Discover the power of control flow statements in JavaScript with this comprehensive chapter. Learn how to use if/else statements, switch statements, and loops to control the flow of your program. Take your programming skills to the next level with this beginner-friendly guide.

Updated: March 11, 2023


This YouTube channel is packed with awesome videos for coders!

Tons of videos teaching JavaScript and coding. Cool live streams!

Click Here to check out the Channel!

Welcome to our tutorial, where we’ll dive deep into the world of JavaScript control flow statements. Control flow statements are a fundamental part of any programming language, including JavaScript. They allow you to control the order in which statements are executed in your program, based on certain conditions or criteria.

In JavaScript, there are three main types of control flow statements:

  • if/else statements
  • switch statements
  • loops.

Let’s explore each of these in detail.

If/Else Statements

If/else statements are used to execute a block of code if a certain condition is true, and a different block of code if the condition is false.

The if…else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

Here’s how it works:

“How Control Flow Statements in JavaScript work”

Here’s a real life example of it:

const age = 18;

if (age >= 18) {
  console.log("You are an adult");
} else {
  console.log("You are not yet an adult");
}

In this example, the code inside the if statement will be executed because the age variable is greater than or equal to 18. If the age variable was less than 18, the code inside the else statement would be executed instead.

Switch Statements

Switch statements are used to execute a block of code based on the value of a variable or expression.

Here is how it works:

“How Control Flow Statements in JavaScript work”

Here’s an example:

const dayOfWeek = "Monday";

switch (dayOfWeek) {
  case "Monday":
    console.log("It's Monday!");
    break;
  case "Tuesday":
    console.log("It's Tuesday!");
    break;
  default:
    console.log("It's another day of the week");
    break;
}

In this example, the code inside the case statement that matches the value of the dayOfWeek variable will be executed. If there is no match, the code inside the default statement will be executed instead.

Loops

Loops are used to execute a block of code multiple times, based on a certain condition. There are two main types of loops in JavaScript: for loops and while loops.

For Loops

Here’s how the for loop works in JavaScript:

“How Control Flow Statements in JavaScript work”

Here’s an example of a for loop that prints the numbers 1 through 5 to the console:

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

In this example, the code inside the for loop will be executed five times, starting with i = 1 and incrementing i by 1 each time, until i is greater than 5.

While Loops

A while loop simply repeats itself while something is true. Theoretically a while loop can loop forever. It continues until the condition is false.

Here’s how the while loop works:

“How Control Flow Statements in JavaScript work”

So you have to make sure your condition changes to false to stop the loop.

Here’s an example of a while loop that prints the numbers 1 through 5 to the console:

let i = 1;

while (i <= 5) {
  console.log(i);
  i++;
}

In this example, the code inside the while loop will be executed as long as the condition i <= 5 is true. The variable i is initialized to 1, and then incremented by 1 each time the loop runs, until i is greater than 5.

While and Do…While Loops

The while loop executes a specified statement as long as the test condition evaluates to true. The do…while loop will first execute the code, then continue while the condition remains true.

Here’s how it works:

![“How Control Flow Statements in JavaScript work”][4]

Imagine you’re creating a web application that includes a feature for users to guess a secret number between 1 and 100. You want the user to keep guessing as long as their guess is not correct.

let secretNumber = Math.floor(Math.random() * 100) + 1; // This generates a random number between 1 and 100
let guess = null;

while (guess !== secretNumber) {
  guess = prompt("Guess the secret number between 1 and 100!"); // This prompts the user to enter a number
  guess = Number(guess); // Convert the string input to a number

  if (guess < secretNumber) {
    alert("Too low! Try again.");
  } else if (guess > secretNumber) {
    alert("Too high! Try again.");
  }
}

alert("Congratulations! You guessed the secret number.");

In this script, the while loop continues prompting the user for their guess as long as it doesn’t match the secret number.

Real-life Example of “do…while” Loop

Consider a scenario where you’re developing a subscription-based service. Even if users don’t initially want to subscribe, you want to offer them a free article. After reading the free article, you prompt them again if they’d like to subscribe.

let isSubscribed = false;

do {
  // code to display one free article to the user
  showFreeArticle();

  // Ask if the user wants to subscribe after reading
  isSubscribed = confirm("Did you enjoy your free article? Subscribe for more!");
} while (!isSubscribed); // If not subscribed, the loop offers another free article

alert("Thank you for subscribing!");

In this example, the do…while loop ensures that users receive at least one free article before being asked to subscribe, and it continues as long as they choose not to.

Both scenarios demonstrate the practical use of while and do…while loops, handling repetitive tasks based on user interaction until certain conditions are met.

Frequently Asked Questions

Can JavaScript conditionals handle multiple conditions?

Yes, JavaScript conditionals can evaluate multiple conditions using logical operators like && (and), || (or), and ! (not).

What’s the difference between == and === in if statements?

The == operator checks equality with type conversion, whereas === checks equality without type conversion, often referred to as “strict equality.”

How can I stop a loop?

Loops can be stopped using the break statement, which exits the loop. Alternatively, the continue statement skips the current iteration and proceeds to the next one.

Conclusion

Control flow statements are a crucial part of JavaScript programming. By understanding how to use if/else statements, switch statements, and loops, you can control the flow of your program and make it more powerful and flexible.

Understanding control flow in JavaScript is essential for creating interactive web applications. While this guide serves as an introduction, practice and application will cement your skills. For complex projects or guidance, don’t hesitate to reach out.