JavaScript Control Flow: A Deep Dive

In JavaScript, control flow determines the order in which statements are executed in a program. Control flow structures allow us to make decisions, loop through data, and execute code conditionally. Let's explore these structures in depth with explanations and multiple examples for better understanding.
1. Conditional Statements
Conditional statements help us execute code based on certain conditions.
1.1 if Statement
The if
statement executes a block of code if a specified condition evaluates to true
.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example 1:
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
Explanation: Since age
is 18, which meets the condition (>= 18
), the message will be printed.
Example 2:
let temperature = 25;
if (temperature > 30) {
console.log("It's a hot day.");
}
Explanation: The condition temperature > 30
is false
, so the code inside if
will not execute.
Example 3:
let num = 0;
if (num) {
console.log("Number is non-zero");
}
Explanation: Since 0
is a falsy value in JavaScript, the condition fails, and nothing is printed.
1.2 if-else Statement
The if-else
statement provides an alternative block of code to execute when the condition is false
.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example 1:
let marks = 45;
if (marks >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Explanation: Since marks
is less than 50, the else
block executes, printing "Fail".
Example 2:
let light = "red";
if (light === "green") {
console.log("Go");
} else {
console.log("Stop");
}
Explanation: The condition fails because light
is "red", so the else
block runs.
Example 3:
let loggedIn = false;
if (loggedIn) {
console.log("Welcome!");
} else {
console.log("Please log in");
}
Explanation: Since loggedIn
is false
, the else
block executes.
1.3 if-else if-else Statement
Used for multiple conditions.
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example 1:
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Explanation: Since score
is 75, the second condition is met, so "Grade: B" is printed.
2. Switch Statement
The switch
statement evaluates an expression and matches it against multiple cases.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no match found
}
Example 1:
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid Day");
}
Explanation: Since day
is 3, "Wednesday" is printed.
3. Looping Statements
JavaScript Loops: A Complete Guide with Real-Life Examples
Loops are one of the most fundamental concepts in JavaScript programming. They allow us to execute a block of code multiple times, making programs more efficient and reducing repetitive tasks.
Types of Loops in JavaScript
JavaScript provides several types of loops, each designed for specific scenarios. Below, we will cover each type of loop in detail, along with syntax and real-life relatable examples to help you understand them better.
1) for Loop
Description:
The for
loop is used when we know in advance how many times we want to execute a block of code. It consists of three parts:
Initialization
Condition
Increment/Decrement
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Real-Life Examples:
Example 1: Counting the number of students in a class
for (let i = 1; i <= 30; i++) {
console.log(`Student ${i} is present`);
}
Example 2: Printing first 10 even numbers
for (let i = 2; i <= 20; i += 2) {
console.log(i);
}
Example 3: Displaying days of the week
const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (let i = 0; i < days.length; i++) {
console.log(days[i]);
}
2) while Loop
Description:
The while
loop executes a block of code as long as the given condition is true. It is used when we do not know beforehand how many times the loop should run.
Syntax:
while (condition) {
// Code to execute
}
Real-Life Examples:
Example 1: Counting down to the New Year
let countdown = 10;
while (countdown > 0) {
console.log(`New Year in ${countdown} seconds`);
countdown--;
}
Example 2: Rolling a dice until we get a six
let dice;
while (dice !== 6) {
dice = Math.floor(Math.random() * 6) + 1;
console.log(`Rolled: ${dice}`);
}
3) do...while Loop
Description:
The do...while
loop is similar to the while
loop, but it ensures that the code runs at least once before checking the condition.
Syntax:
do {
// Code to execute
} while (condition);
Real-Life Examples:
Example 1: Asking a user for a password until they enter the correct one
let password;
do {
password = prompt("Enter your password:");
} while (password !== "secure123");
console.log("Access granted");
Example 2: Tossing a coin until we get heads
let toss;
do {
toss = Math.random() > 0.5 ? 'Heads' : 'Tails';
console.log(`Coin toss: ${toss}`);
} while (toss !== 'Heads');
4) for...in Loop
Description:
The for...in
loop is used to iterate over the properties of an object.
Syntax:
for (let key in object) {
// Code to execute
}
Real-Life Examples:
Example 1: Printing details of a student
const student = {
name: "John",
age: 16,
grade: "10th",
};
for (let key in student) {
console.log(`${key}: ${student[key]}`);
}
Example 2: Listing a shopping cart items with prices
const cart = {
apple: 30,
banana: 10,
mango: 50,
};
for (let item in cart) {
console.log(`${item} costs ${cart[item]} rupees`);
}
5) for...of Loop
Description:
The for...of
loop is used to iterate over iterable objects like arrays and strings.
Syntax:
for (let value of iterable) {
// Code to execute
}
Real-Life Examples:
Example 1: Printing names of students in a class
const students = ["Amit", "Neha", "Rahul", "Pooja"];
for (let student of students) {
console.log(student);
}
Example 2: Displaying characters of a word
const word = "JavaScript";
for (let letter of word) {
console.log(letter);
}
6) break and continue Statements
Description:
break
: Exits the loop immediately.continue
: Skips the current iteration and moves to the next one.
Real-Life Examples:
Example 1: Stopping a loop when a specific number is found
for (let i = 1; i <= 10; i++) {
if (i === 5) break;
console.log(i);
}
Example 2: Skipping Sundays while printing days of a week
const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (let day of days) {
if (day === 'Sunday') continue;
console.log(day);
}
Conclusion
Loops in JavaScript are powerful tools that help reduce repetitive code and make programming more efficient. By using for
, while
, do...while
, for...in
, and for...of
loops wisely, developers can handle various programming tasks effectively. The break
and continue
statements further allow fine-tuned control over loop execution.
This guide provides a deep understanding of JavaScript's control flow, helping beginners grasp the concepts through well-explained examples. Happy coding!
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟