Introduction
- The if-else statement in JavaScript executes a certain code block based on a certain condition.
- When the condition is evaluated as true, the code block inside the
if
statement is executed. - If the condition is false, the
else
block runs instead.
Note: The if
statement can be used without an else
statement if no action is needed when the condition is false.
Syntax:
if(condition){ //Executes when condition is true }else{ //Executes when condition is false }
1. simple(if) statement
To check one condition and execute code when it’s true
, you can use a standalone if
statement.
Example:
let temp = 31; if(temp>30){ console.log("It's a sunny day."); }
This code will output the statement ‘It’s a sunny day.’ when the temperature is higher than 30.
Output:
It's a sunny day.
2. if-else statement
An else
statement can follow an if
statement to execute code when the if
condition is false.
Example:
let cadage = 20; if(cadage>=18){ console.log("Valid Age"); }else{ console.log("Invalid Age"); }
Output:
Valid Age
As the age of the candidate is 20 which is greater than 18. So he/she is eligible to apply for a particular job.
3. else-if statement
To check multiple conditions, use multiple
else if
statements.Example:
let precentage = 85; if (precentage >= 90) { console.log("Grade: A"); } else if (precentage >= 75) { console.log("Grade: B"); } else if (precentage >= 50) { console.log("Grade: C"); } else { console.log("Grade: F"); }
Output:
Grade: B
As the percentage is 85 which is smaller than 90 and greater than 75. So the grade is B.
4. Nested if-else statement
To check on multiple conditions nesting of if-else is used.
Example:
let num = 5; let result; if(num > 0){ if(num%2 === 0){ result = "Positive even number"; }else{ result = "Positive odd number"; } }else{ if (num < 0){ result = "Negative number"; }else{ result = "The number is zero"; } } console.log(result);
Output:
Positive odd number
Summary:
- Use
if
when you have a single condition to check. - Use
if-else
for two possible outcomes. - Use else-if for multiple conditions.
- Use nested
if-else
statements for more complex conditions.