Advertisement

Google Ad Slot: content-top

JS If Else


if Statement:

The if statement is used to execute a block of code only if a specified condition evaluates to true.


Syntax:

if (condition) { 
   // Code to execute if condition is true 
}
Example
let age = 20;

if (age >= 18) {
console.log("You are eligible to vote.");
}
Try it yourself

if...else Statement:

The if...else statement allows you to execute one block of code if the condition is true and another block if the condition is false


Syntax:

if (condition) { 
   // Code to execute if condition is true 
} else { 
   // Code to execute if condition is false 
}
Example
let age = 20;

if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}

Try it yourself

if...else if...else Statement

For multiple conditions, you can use else if blocks.


Syntax:

if (condition) { 
   // Code to execute if condition is true 
} else if(condition2) { 
   // Code to execute else if condition is true 
} else {
   // Code to execute if and else if condition is false 
}


Example
let score = 85;

if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}

Try it yourself

Ternary Operator:

For simple if...else conditions, you can use the ternary operator:

Example
let age = 20;
let message = age >= 18 ? "You are an adult." : "You are a minor.";
console.log(message);
Try it yourself

Nested if...else:

You can nest if...else statements inside each other, but keep readability in mind.

Example
let number = 10;

if (number > 0) {
if (number % 2 === 0) {
console.log("The number is positive and even.");
} else {
console.log("The number is positive and odd.");
}
} else {
console.log("The number is not positive.");
}
Try it yourself

Logical Operators in Conditions

You can use logical operators (&&, ||, !) to combine conditions.

1.AND (&&):

Example
let age = 25;

if (age > 18 && age < 30) {
console.log("You are in your 20s.");
}
Try it yourself

2.OR (||):

Example
let day = "Saturday";

if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
Try it yourself

3.NOT (!):

Example
let isRaining = false;

if (!isRaining) {
console.log("You can go outside without an umbrella.");
}
Try it yourself