Javascript Conditional statements (if/else, switch)
JavaScript provides two conditional statements for executing different actions based on different conditions: if/else and switch.
if/else statement:
The if statement is used to execute a block of code if the condition specified in the if statement evaluates to true. If the condition is false, then the code inside the if statement will not execute.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
Output:
x is greater than 5
switch statement:
The switch statement is used to perform different actions based on different conditions. It allows the code to execute different parts of the code based on different conditions.
Syntax:
var a = 10;
var b = a;
console.log(b); // Output: 10
The value of a, which is 10 in the case above, is given to b.
As demonstrated in the example below, variables can also be used to store reference data types like arrays and objects:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
default:
// Code to execute if expression does not match any value
}
Example:
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
case "Wednesday":
console.log("Today is Wednesday");
break;
default:
console.log("Invalid day");
}
Output:
Today is Monday