Skip to main content

Branching

Branches are used to execute particular code depending on the condition. The principle is simple: the condition result is converted to a boolean, true or false, after which the program executes this or that branch.

if statement

if syntax
if (condition) {
// if body
}

The input data that is converted to a boolean is called a condition. The condition is placed after the if statement in parentheses. If the condition is converted to true, the code in curly braces of the if body is then executed.

let cost = 0;
const subscription = "pro";

if (subscription === "pro") {
cost = 100;
}

console.log(cost); // 100

If the condition is converted to false, the code in curly braces will be skipped.

let cost = 0;
const subscription = "free";

if (subscription === "pro") {
cost = 100;
}

console.log(cost); // 0

if...else statement

if...else syntax
if (condition) {
// if body
} else {
// else body
}

The if syntax is extended; if the condition is converted to false, the code in curly braces after the else statement will be executed.

let cost;
const subscription = "free";

if (subscription === "pro") {
cost = 100;
} else {
cost = 0;
}

console.log(cost); // 0

If the condition is converted to true, the body of the else block is ignored.

let cost;
const subscription = "pro";

if (subscription === "pro") {
cost = 100;
} else {
cost = 0;
}

console.log(cost); // 100

else...if statement

else...if syntax

The if ... else statement can check and react to the fulfillment or non-fulfillment of only one condition.

The else ... if block enables you to add after else another if statement with a condition. At the end of the chain, there can be a classic else block, which will be executed only if none of the conditions is converted to true.

let cost;
const subscription = "premium";

if (subscription === "free") {
cost = 0;
} else if (subscription === "pro") {
cost = 100;
} else if (subscription === "premium") {
cost = 500;
} else {
console.log("Invalid subscription type");
}

console.log(cost); // 500

After finding the first true, checks will stop and only the script corresponding to the true condition will run. Therefore, this should be read as: looking for the first match of a condition, ignoring everything else.