Control Flow and Loops in JavaScript
In JavaScript, control flow refers to the order in which the program's statements are executed. Control flow determines how the code is processed based on certain conditions and decisions. Loops, on the other hand, allow you to repeat a block of code multiple times, making your programs more efficient and dynamic.
In this blog, we’ll walk through the basic concepts of control flow and loops in JavaScript. Whether you are just starting or need a refresher, this guide will help you understand the key concepts with examples that you can experiment with.
What is Control Flow?
Control flow in JavaScript determines the order of execution of statements based on conditions. There are several key structures used to control the flow of code:
- Conditionals (if, else, else if) – Decide what code to run based on whether a condition is true or false.
- Switch – Used to perform different actions based on different conditions.
Let’s break them down.
1. The if
Statement
The if
statement evaluates a condition. If the condition is true
, the code inside the block is executed. If it’s false
, the block is skipped.
Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult!");
}
Breakdown:
- if (age >= 18): Checks if the value of
age
is greater than or equal to 18. - If true, it runs
console.log("You are an adult!")
.
2. The else
Statement
The else
statement follows an if
statement and runs if the condition in the if
is false
.
Example:
let age = 16;
if (age >= 18) {
console.log("You are an adult!");
} else {
console.log("You are a minor.");
}
Breakdown:
- else: This block will run if the
if
condition is false.
3. The else if
Statement
Sometimes, you need to check multiple conditions. This is where else if
comes in handy. It allows you to test more than one condition.
Example:
let age = 25;
if (age >= 65) {
console.log("You are a senior citizen.");
} else if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Breakdown:
- else if: Tests an alternative condition if the first one is false.
- else: Runs if none of the conditions are met.
4. The switch
Statement
A switch
statement evaluates an expression and compares it with different cases. If a match is found, the corresponding code block runs.
Example:
let fruit = "apple";
switch(fruit) {
case "apple":
console.log("You chose an apple!");
break;
case "banana":
console.log("You chose a banana!");
break;
default:
console.log("Unknown fruit.");
}
Breakdown:
- switch(fruit): Evaluates the value of
fruit
. - case "apple": If
fruit
equals"apple"
, the first block of code runs. - break: Stops the
switch
statement from running further once a case is matched. - default: A fallback option if none of the cases match.
What Are Loops?
Loops are used when you want to run a block of code repeatedly based on a condition. There are several types of loops in JavaScript:
- For Loop
- While Loop
- Do-While Loop
- For...of and For...in Loops
Let's dive into each of them.
1. The for
Loop
The for
loop is the most common type of loop, and it runs a block of code a set number of times. It has three parts:
- Initialization: Sets up the loop.
- Condition: Continues the loop while the condition is true.
- Iteration: Increases or decreases the loop counter after each run.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Breakdown:
- let i = 0: Initializes the loop counter
i
to 0. - i < 5: The loop runs while
i
is less than 5. - i++: Increments
i
by 1 after each loop.
This will print:
0
1
2
3
4
2. The while
Loop
The while
loop continues to run as long as a specified condition is true
. If the condition is never met, the loop will never run.
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Breakdown:
- The loop runs as long as
i < 5
. - The counter
i
is incremented after each iteration, ensuring the loop eventually ends.
3. The do...while
Loop
The do...while
loop is similar to the while
loop, except that it guarantees the block of code will run at least once, even if the condition is false.
Example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Breakdown:
- The block inside the
do
will always run once, and then it checks the condition to decide if it should continue.
4. The for...of
and for...in
Loops
for...of
: Loops through the values of an iterable object (like an array).for...in
: Loops through the keys of an object.
Example of for...of
:
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Example of for...in
:
let person = {
name: "Alice",
age: 25,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Breakdown:
for...of
iterates over values in an array or iterable.for...in
iterates over the keys in an object.
Control Flow and Loops in Action
Let’s combine control flow and loops into a simple example. Suppose we want to check numbers from 1 to 10 and print whether they are odd or even:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i + " is even.");
} else {
console.log(i + " is odd.");
}
}