Skip to main content

Control Flow

In simpler terms, control flow is like the flowchart of your program. It dictates the sequence of actions taken by the program as it runs, determining which lines of code get executed and in what order.

1) Sequential Execution

By default, JavaScript executes statements in the order they appear in the code, from top to bottom. This sequential execution forms the basis of control flow in JavaScript.

console.log('hi');
console.log('this is faith');

The result will be:

"hi"
"this is faith"

2) Conditional Execution // Branching

Conditional statements allow you to execute different blocks of code based on certain conditions.

The most common conditional statement in JavaScript is the if-else statement.

if... else if... else ...

if (condition) {
// Code to execute if condition is true
} else if (another condition){
// Code to execute if first condition is false
} else {
// Code to execute if all conditions are false
}

There's also other ways to perform control flow:

Ternary Operator - ... ? ... : ...

// condition ? expression1 : expression2
let x = 10;

x > 2 ? console.log('more than 2') : console.log('less than 2');

Nullish Coalescing Operator - ??

// expression ?? defaultValue

let x = 10;
let result = x > 2 ? 'it is bigger than 2!' : 'it is not bigger than 2!';
console.log(result);

Optional Chaining - (?.)

The optional chaining operator allows you to safely access nested properties of objects without worrying about the possibility of encountering null or undefined.

let user = { name: 'John', address: { city: 'New York' } };
let city = user.address?.city;

3) Switch Statements

switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if expression doesn't match any case
}

4) Loops

Loops are used to repeatedly execute a block of code as long as a specified condition is true.

JavaScript supports several types of loops, including for, while, and do-while loops.

For Loops

for (initialization; condition; increment / decrement) {
// Code to execute repeatedly
}

for (let i = 0; i < 5; i++) {
console.log('hi');
}

While Loops

while (condition) {
// Code to execute while condition is true
}

x = 10;

while (x < 10) {
console.log('less than 10!');
}