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)
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.");
}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.");
}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");
}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");
}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);
}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++;
}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);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]);
}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);
}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);
}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);
}1. What is the difference between if and switch statements?
Both if and switch statements are used for conditional execution of code blocks.
-
ifStatement: Evaluates boolean expressions and is suitable for complex conditions.Example:
let age = 25;
if (age < 18) {
console.log("Minor");
} else if (age >= 18 && age < 65) {
console.log("Adult");
} else {
console.log("Senior");
}-
switchStatement: Evaluates an expression against multiple possible values. It's cleaner when checking a variable against many constant values.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");
}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.
-
forLoop: Best when the number of iterations is known.Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}-
whileLoop: Best when the number of iterations is not known in advance.(Wikipedia)Example:
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)Example:
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)Example:
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
// Outputs: 0 1 3 44. How do for...in and for...of loops differ?
-
for...in: Iterates over enumerable properties of an object (keys).Example:
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:
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:
condition ? expressionIfTrue : expressionIfFalse;Example:
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:
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!
let sum = 0;
let i = 1;
while (i <= 100) {
sum += i;
i++;
}
console.log("The sum is:", sum); // Outputs: The sum is: 50508. 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)
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)
These questions and answers should provide a solid understanding of control flow in JavaScript and prepare you for related interview topics.
- Use
if,else if, andelseto execute code blocks based on conditions. - Use
switchfor multiple condition checks against a single expression. - Use loops (
for,while,do...while) to execute code repeatedly. - Use
for...into iterate over object properties. - Use
for...ofto iterate over iterable objects like arrays. - Use
breakto exit loops orswitchstatements prematurely. - Use
continueto skip the current iteration in loops.(Medium, Codeguage, Wikipedia)
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!