learn-javascript

📘 04 - Control Flow in JavaScript

Control flow determines the order in which individual statements, instructions, or function calls are executed or evaluated in a program. JavaScript provides several control flow statements that allow you to make decisions, execute code conditionally, and perform repetitive tasks. (Javascript Cheatsheet, Medium)


✅ Conditional Statements

1. if Statement

The if statement executes a block of code if a specified condition is true.(DEV Community)

Syntax:

if (condition) {
  // code to execute if condition is true
}

Example:

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

2. if...else Statement

The if...else statement executes one block of code if a condition is true, and another block if the condition is false.(DEV Community)

Syntax:

if (condition) {
  // code if condition is true
} else {
  // code if condition is false
}

Example:

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

3. if...else if...else Statement

The if...else if...else statement allows you to test multiple conditions.(DEV Community)

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:

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

4. switch Statement

The switch statement evaluates an expression and executes code blocks based on matching case labels.(web.dev)

Syntax:

switch (expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // default code block
}

Example:

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

🔁 Looping Statements

1. for Loop

The for loop repeats a block of code a specified number of times.(DEV Community)

Syntax:

for (initialization; condition; increment) {
  // code block to be executed
}

Example:

for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}

2. while Loop

The while loop executes a block of code as long as a specified condition is true.(DEV Community)

Syntax:

while (condition) {
  // code block to be executed
}

Example:

let i = 0;
while (i < 5) {
  console.log("Iteration:", i);
  i++;
}

3. do...while Loop

The do...while loop is similar to the while loop, but it executes the code block once before checking the condition.(Wikipedia)

Syntax:

do {
  // code block to be executed
} while (condition);

Example:

let i = 0;
do {
  console.log("Iteration:", i);
  i++;
} while (i < 5);

4. for...in Loop

The for...in loop iterates over the enumerable properties of an object.(Wikipedia)

Syntax:

for (let key in object) {
  // code block to be executed
}

Example:

const person = { name: "Alice", age: 25 };
for (let key in person) {
  console.log(key + ": " + person[key]);
}

5. for...of Loop

The for...of loop iterates over iterable objects like arrays, strings, etc.(Medium)

Syntax:

for (let value of iterable) {
  // code block to be executed
}

Example:

const numbers = [1, 2, 3];
for (let num of numbers) {
  console.log(num);
}

🔄 Control Flow Modifiers

1. break Statement

The break statement terminates the current loop or switch statement.(GeeksforGeeks)

Example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

2. continue Statement

The continue statement skips the current iteration of a loop and continues with the next iteration.

Example:

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(i);
}

💬 JavaScript Control Flow Interview Questions & Answers

1. What is the difference between if and switch statements? Both `if` and `switch` statements are used for conditional execution of code blocks. * **`if` Statement**: Evaluates boolean expressions and is suitable for complex conditions. **Example:** ```javascript let age = 25; if (age < 18) { console.log("Minor"); } else if (age >= 18 && age < 65) { console.log("Adult"); } else { console.log("Senior"); } ``` * **`switch` Statement**: Evaluates an expression against multiple possible values. It's cleaner when checking a variable against many constant values. **Example:** ```javascript 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("Another day"); } ```
2. How does a for loop differ from a while loop? Both loops are used for iteration but differ in syntax and typical use cases. * **`for` Loop**: Best when the number of iterations is known. **Example:** ```javascript for (let i = 0; i < 5; i++) { console.log(i); } ``` * **`while` Loop**: Best when the number of iterations is not known in advance.([Wikipedia][1]) **Example:** ```javascript let i = 0; while (i < 5) { console.log(i); i++; } ```
3. What is the purpose of the break and continue statements? * **`break`**: Terminates the current loop or switch statement.([GeeksforGeeks][2]) **Example:** ```javascript for (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i); } // Outputs: 0 1 2 3 4 ``` * **`continue`**: Skips the current iteration and continues with the next one.([GeeksforGeeks][3]) **Example:** ```javascript for (let i = 0; i < 5; i++) { if (i === 2) continue; console.log(i); } // Outputs: 0 1 3 4 ```
4. How do for...in and for...of loops differ? * **`for...in`**: Iterates over enumerable properties of an object (keys). **Example:** ```javascript const obj = { a: 1, b: 2 }; for (let key in obj) { console.log(key); // Outputs: 'a', 'b' } ``` * **`for...of`**: Iterates over iterable objects like arrays, strings, etc. **Example:** ```javascript const arr = [1, 2, 3]; for (let value of arr) { console.log(value); // Outputs: 1, 2, 3 } ```
5. What is a ternary operator, and how is it used? The ternary operator is a concise way to perform conditional assignments. **Syntax:** ```javascript condition ? expressionIfTrue : expressionIfFalse; ``` **Example:** ```javascript let age = 20; let beverage = age >= 18 ? "Beer" : "Juice"; console.log(beverage); // Outputs: "Beer" ```
6. How does the do...while loop work? The `do...while` loop executes the code block once before checking the condition, ensuring that the block is executed at least once. **Example:** ```javascript let i = 0; do { console.log(i); i++; } while (i < 5); ```
7. Can you provide an example of using a while loop to calculate the sum of numbers from 1 to 100? Certainly! ```javascript let sum = 0; let i = 1; while (i <= 100) { sum += i; i++; } console.log("The sum is:", sum); // Outputs: The sum is: 5050 ```
8. How would you use a do...while loop to prompt a user until they enter the correct password? Here's how you can implement it:([web.dev][4]) ```javascript let password; do { password = prompt("Enter your password:"); } while (password !== "correctPassword"); console.log("Access granted."); ``` This loop will continue prompting the user until they enter "correctPassword".([Medium][5])

These questions and answers should provide a solid understanding of control flow in JavaScript and prepare you for related interview topics.

🧠 Summary

Understanding and effectively using control flow statements is fundamental to writing efficient and logical JavaScript code.


Feel free to reach out if you have any questions or need further clarification on any of these topics!