Creating Branches

A Single Branch -> if statement
if statementlet num = prompt("Enter a value");
if (num > 100) {
console.log("Wow, that is a large number!");
}
console.log(`Your number is: ${num}`);In this situation we created a single branch. The event that belongs to our if statement only executes if our given variable num is greater than 100.
Any code that belongs to a coding construct is called a "code block"
Binary Branch -> if ... else statement
if ... else statement
To create a program with two pathways where we can have an event occurs when our if statement evaluates to false is using an else statement.
let num = prompt("Enter a value");
if (num > 100) {
console.log("Wow, that is a large number!");
} else {
console.log("Darn, that is a small number!");
}
console.log(`Your number is: ${num}`);An else statement is not a requirement for all if clauses; however, you can use it if you want something to happen when the condition it is attached to is evaluated to false.
Multiple Branches

To create a program with multiple, BUT RELATED pathways, we can incorporate an else if statement.
let num = prompt("Enter a value");
if (num == 69) {
console.log("Nice!");
} else if (num > 100) {
console.log("Wow, that is a large number!");
} else {
console.log("Darn, that is a small number!");
}
console.log(`Your number is: ${num}`);The program above would work as follows
It outputs
Nice!only if num was equal to 69It outputs
Wow, that is a large number!, only ifnumis not equal to 69 and greater than 100It outputs
Darn, that is a small number!, only ifnumis not equal to 69 andnumis less than 100
Recommended Reading
Conditional Branching (Link)
Last updated