An "else statement" in programming, including languages like JavaScript, is used in conjunction with an "if statement" to provide an alternative block of code to execute when the condition of the "if statement" evaluates to false. It allows for creating branching logic where different code paths are taken based on whether the initial condition is true or false.
Else statement
The basic syntax of an "if-else statement" in JavaScript is as follows:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Here's how the "if-else statement" works:
- The condition is evaluated to either true or false.
- If the condition is true, the code within the first block (after if) is executed, and the code within the else block is skipped.
- If the condition is false, the code within the else block is executed, and the code within the first block is skipped.
var age = 17;
if (age >= 18) {
console.log("You're eligible to vote!");
} else {
console.log("You're not yet eligible to vote.");
}
In this example, if the age is 18 or older, the message "You're eligible to vote!" will be printed. Otherwise, the message "You're not yet eligible to vote." will be printed.
×