Control Structures

Control Structures

Control structures in JavaScript are constructs that allow you to control the flow of execution in your code. They enable you to make decisions, repeat tasks, and handle different scenarios based on specific conditions. They include

1. Conditional statements

Conditional statements allow you to execute different blocks of code based on whether a specified condition evaluates to true or false. The primary conditional statements in JavaScript are

  • ‘If’ statement: executes a block of code if a specific condition is true.

  • ‘else if’ statement: Allows you to specify additional conditions to test if previous conditions are false.

  • ‘else’ statement: provides a default block of code to execute if none of the previous conditions are true.

2. Switch

The switch statement provides a way to execute different code blocks based on the value of an expression. It's especially useful when you have multiple cases to evaluate against a single expression

The switch statement can be more efficient than multiple ‘if-else if’ statements when dealing with a large number of cases

The ‘break’ statement is important to prevent fall-through behavior where the execution continuous to the next case even after a match

3. break

The break statement is used to end the execution of a loop or a switch statement. It exits the current loop or switch block and transfers control to the statement immediately following the terminated statement.

4. Continue

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. It allows you to skip certain iterations based on specific conditions selectively

5. Loops

Loops are control structures that allow you to repeat a block of code multiple times until a specified condition is met.

  • ‘For’ loop

The ‘for’ loop is typically used when you know how many times you want to execute the loop

Example

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

console.log(i); // Output: 0, 1, 2, 3, 4

}

  • ‘While’ loop

The while loop is used when you want to execute a block of code while a condition is true. It's suitable when you don't know in advance how many times the loop will be executed

Example

let i = 0;

while (i < 5) {

console.log(i); // Output: 0, 1, 2, 3, 4

i++;

}

  • ‘do-while’ loop

The do-while is similar to the ‘while’ loop but it always executes the block of code at least once before checking the condition.

Example

let i = 0;

do {

console.log(i); // Output: 0, 1, 2, 3, 4

i++;

} while (i < 5);