JavaScript Control Flow
Last updated:
return
The return
statement ends function execution and specifies a value to be returned to the function caller.
function add(a, b) {
return a + b;
// code after return statement will not be executed
}
Conditional Statements
if-else statement
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
let age = 10;
if (age < 18) {
console.log("Person is a child");
} else {
console.log("Person is an adult");
}
NB: For simple conditions, the ternary operator can be used instead.
Can be “chained” to satisfy multiple conditions:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Switch statement
Select one of many code blocks to be executed:
switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
// other cases here
// ...
default:
// code to be executed if expression doesn't match any of the cases
}
let day = "Sunday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Today is weekday");
break;
case "Saturday":
case "Sunday":
console.log("Today is weekend");
break;
default:
console.log("Invalid day");
}
// prints: "Today is weekend"
NB: Cases without a break statement simple “fall-through” to the next case.
Loops
for loop
for (initialization; condition; increment/decrement) {
// code block to be executed
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
while loop
NB: the block will never be executed if the initial condition is not met
while (condition) {
// code to be executed
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do…while loop
NB: the block will be executed at least once, even if the condition is false
do {
// code to be executed
} while (condition);
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Iterations
Can iterate over the elements of an “iterable” object (eg: arrays, objects, sets).
for…in loop
const person = {
name: 'Charlie',
city: 'London'
};
for (const prop in person) {
console.log(`${prop}: ${person[prop]}`);
}
for…of loop
const people = ['Charlie', 'Paul'];
for (const person of people) {
console.log(person);
}
forEach loop
Iterate over an array via an anonymous function:
const people = ['Charlie', 'Paul'];
people.forEach((person) => {
console.log(person);
});
Break & Continue
Orovide a way to alter the flow of a loop or iteration in certain conditions:
- break terminates the loop
- continue skip the rest of the current iterations and proceeds to the next
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
console.log('Found 3!');
break; // terminate the loop
}
if (numbers[i] % 2 === 0) {
continue; // skip even numbers
}
console.log(numbers[i]);
}
// prints
// 1
// Found 3!