Conditional Statements

Conditional statements allow you to control the flow of execution based on certain conditions. JavaScript provides the following conditional statements:

if Statement

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

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

if...else Statement

The if...else statement executes one block of code if the condition is true, and another block if the condition is false.

 

let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

else if Statement

The else if statement allows you to check multiple conditions in a chain.

let grade = 85;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else {
console.log("F");
}

 

switch Statement

The switch statement is an alternative to multiple if...else statements. It evaluates an expression and executes the associated block of code for the matching case.

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");
}

Loops

Loops are used to execute a block of code repeatedly as long as a certain condition is met. JavaScript provides several types of loops:

for Loop

The for loop is used to execute a block of code a specific number of times.

for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0 1 2 3 4
}

while Loop

The while loop executes a block of code as long as a specified condition is true.

let count = 0;
while (count < 5) {
console.log(count); // Output: 0 1 2 3 4
count++;
}

 

do...while Loop

The do...while loop is similar to the while loop, but it executes the block of code at least once, even if the condition is false.

let count = 0;
do {
console.log(count); // Output: 0 1 2 3 4
count++;
} while (count < 5);

break and continue Statements

The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and move to the next one.

for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Output: 1 3 5
}

In the next chapter, we'll explore functions, which are essential building blocks for modular and reusable code in JavaScript.