This article covers the following concepts:
if
statement executes a block of JavaScript code if a condition is true.else if
statement.else
statement.if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
const x = 5;
if (x > 5) {
console.log("x is greater than 5");
} else if (x < 5) {
console.log("x is less than 5");
} else {
console.log("x is 5");
}
To compare different values, we can use comparison operators.
For example
if (time < 11) {
greeting = "Good morning";
} else if (time < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
if (mood === "sleepy" && tirednessLevel > 8) {
console.log("time to sleep");
} else {
console.log("not bed time yet");
}
We can use a ternary operator to simplify an if…else statement.
condition ? console.log("true") : console.log("false");
const x = 5;
const color = x > 5 ? "red" : "blue";
console.log(color); // blue
The switch
statement compares multiple values. It’s another way to evaluate conditions.
case
keyword checks if the expression matches the specified value that comes after it.default
statement will run.break
keyword tells the computer to exit the block.switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
const x = 5;
const color = x > 5 ? "red" : "blue";
switch (color) {
case "red":
console.log("Color is red");
break;
case y:
console.log("Color is blue");
break;
default:
console.log("Don't know the color");
}