The if...else
statement in JavaScript is a conditional statement that allows you to execute different blocks of code based on whether a certain condition is true or false.
Here’s the basic syntax:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
The condition
in the if
statement can be any expression that evaluates to a Boolean value (true or false). If the condition is true, the code inside the first block will be executed. If the condition is false, the code inside the second block (the else
block) will be executed.
Here’s an example that demonstrates how the if...else
statement works:
let num = 10;
if (num % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
In this example, the condition
is num % 2 === 0
, which checks whether num
is even or odd. Since num
is equal to 10, which is even, the code inside the first block (console.log("The number is even.")
) will be executed, and the output will be “The number is even.”