Javascript else statement
Created By: chatGPT
In JavaScript, the
else
statement is used to specify a block of code that will run if the condition of the preceding if
statement evaluates to false. This is useful for defining alternative actions that should be taken based on certain conditions.if (condition) {
// block of code executed if condition is true
} else {
// block of code executed if condition is false
}
You can also use the
else if
statement if you need to check for additional conditions. This allows for multiple possible paths of execution in your code.if (condition1) {
// executed if condition1 is true
} else if (condition2) {
// executed if condition1 is false and condition2 is true
} else {
// executed if both condition1 and condition2 are false
}
Here’s an example of how to use the
if
, else if
, and else
statements in a simple program that checks a person's age:let age = 20;
if (age < 13) {
console.log('You are a child.');
} else if (age < 20) {
console.log('You are a teenager.');
} else {
console.log('You are an adult.');
}
In this code, we check the age variable:
- If age is less than 13, it logs "You are a child."
- If age is less than 20 but greater than or equal to 13, it logs "You are a teenager."
- For any other value of age, it logs "You are an adult."
let age = 25;
if (age < 13) {
console.log('You are a child.');
} else if (age < 20) {
console.log('You are a teenager.');
} else {
console.log('You are an adult.');
}