The if...else
statement is used to perform different actions based on different conditions. It allows you to test if a condition is true or false and execute code accordingly.
1. Basic Syntax of If Else:
if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
Example:
let x = 10; if (x > 5) { console.log("x is greater than 5"); } else { console.log("x is not greater than 5"); }
Explanation:
- The condition
x > 5
is true, so the message"x is greater than 5"
will be logged.
2. Else If:
You can add multiple conditions using else if
to check for different possibilities.
Syntax of If Else If:
if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition2 is true } else { // Code to execute if all conditions are false }
Example:
let age = 18; if (age < 18) { console.log("You are a minor"); } else if (age >= 18 && age <= 65) { console.log("You are an adult"); } else { console.log("You are a senior"); }
Explanation:
- If the age is less than 18, the message
"You are a minor"
is printed. - If the age is between 18 and 65, the message
"You are an adult"
is printed. - If the age is greater than 65, the message
"You are a senior"
is printed.
3. Nested If Else:
You can also nest if...else
statements within each other to check for multiple conditions.
Example:
let x = 10; let y = 20; if (x > y) { console.log("x is greater than y"); } else { if (x < y) { console.log("x is less than y"); } else { console.log("x is equal to y"); } }
Explanation:
- First, it checks if
x > y
. If false, it checks ifx < y
. If false, it concludes thatx
is equal toy
.
4. Ternary Operator (Shortcut for If Else):
The ternary operator provides a more concise way of writing if...else
statements. It’s used for simple conditions.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example:
let age = 18; let result = age >= 18 ? "Adult" : "Minor"; console.log(result); // "Adult"
Explanation:
- If the condition
age >= 18
is true,"Adult"
is assigned toresult
, otherwise"Minor"
is assigned.
Conclusion:
if...else
allows you to control the flow of code based on conditions.else if
helps you handle multiple conditions.- Nested
if...else
enables deeper decision-making logic. - The ternary operator provides a shorter form for simple conditions.