Control Flow in JavaScript – Loops and Conditions

Robert MuendoRobert Muendo
4 min read

Introduction

Control flow is the backbone of any programming language, determining the order in which code is executed. In JavaScript, control flow allows us to create dynamic, interactive applications by making decisions and repeating actions based on certain conditions.

In this blog, we'll explore two fundamental aspects of control flow:

  1. Conditional Statements : How to execute code based on specific conditions.

  2. Loops : How to repeat code until a condition is met.

We'll also build a simple "Guess the Number" game to apply these concepts practically. By the end of this post, you'll have a solid understanding of how to use control flow in JavaScript!


Understanding Conditional Statements

Conditional statements allow your program to make decisions. They check whether a condition is true or false and execute code accordingly.

1. If Statement

The if statement runs a block of code only if a specified condition is true.

let age = 18;

if (age >= 18) {

console.log("You are eligible to vote!");

}

2. If-Else Statement

The if-else statement provides an alternative block of code to execute when the condition is false.

let score = 75;

if (score >= 60) {

console.log("You passed the exam!");

} else {

console.log("You need to study more.");

}

3. Else-If Statement

Use else-if to handle multiple conditions.

let grade = 85;

if (grade >= 90) {

console.log("Grade: A");

} else if (grade >= 80) {

console.log("Grade: B");

} else if (grade >= 70) {

console.log("Grade: C");

} else {

console.log("Grade: F");

}

4. Switch Statement

The switch statement is useful for testing a variable against multiple values.

let day = "Monday";

switch (day) {

case "Monday":

console.log("Start of the workweek.");

break;

case "Friday":

console.log("End of the workweek.");

break;

default:

console.log("It's just another day.");

}

Exploring Loops

Loops enable you to execute a block of code repeatedly until a condition is met. This is especially useful for automating repetitive tasks.

1. For Loop

The for loop is ideal when you know how many times you want to iterate.

for (let i = 1; i <= 5; i++) {

console.log(`Counting: ${i}`);

}

2. While Loop

The while loop runs as long as a condition remains true.

let count = 1;

while (count <= 5) {

console.log(`While loop: ${count}`);

count++;

}

3. Do-While Loop

The do-while loop ensures that the code block runs at least once before checking the condition.

let num = 1;

do {

console.log(`Do-while loop: ${num}`);

num++;

} while (num <= 5);

Building a Guess the Number Game

Now that we've covered the basics of control flow, let's put it into practice by building a simple "Guess the Number" game. The goal is for the user to guess a randomly generated number within a certain range.

Game Logic

  1. Generate a random number between 1 and 10.

  2. Prompt the user to input their guess.

  3. Use conditional statements to check if the guess is correct, too high, or too low.

  4. Allow the user to keep guessing until they get it right.

Code Example

// Generate a random number between 1 and 10

let secretNumber = Math.floor(Math.random() * 10) + 1;

let guess = null;

// Loop until the user guesses correctly

while (guess !== secretNumber) {

guess = parseInt(prompt("Guess the number (1-10):"));

if (isNaN(guess)) {

alert("Please enter a valid number!");

} else if (guess < secretNumber) {

alert("Too low! Try again.");

} else if (guess > secretNumber) {

alert("Too high! Try again.");

} else {

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

}

}

Visualizing Control Flow with Flowcharts

Flowcharts are a great way to visualize how control flow works. Below are some examples:

Flowchart for If Statement

Flowchart for If-Else Statement

Flowchart for Else-If Statement

Flowchart for Switch Statement

Flowchart for While Loop

Flowchart for do-While Loop

Flowchart of a for Loop


Conclusion

Control flow is essential for writing dynamic and interactive JavaScript programs. By mastering conditional statements and loops, you can create logic-driven applications that respond to user input and perform complex tasks.

In the next blog, we'll dive deeper into functions and scope, further expanding your JavaScript toolkit. Stay tuned!


Bonus Exercise

Try modifying the "Guess the Number" game to limit the number of attempts the user has. For example, give them 5 chances to guess the number before ending the game.

10
Subscribe to my newsletter

Read articles from Robert Muendo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Robert Muendo
Robert Muendo