JavaScript If-else

The JavaScript if-else statement is used for conditional execution. It allows you to execute a certain block of code if a condition is true, and a different block of code if the condition is false.

This is a basic if-else syntax:

if (condition) { // code to be executed if the condition is true }
 else { // code to be executed if the condition is false }

The condition is an expression that evaluates to a Boolean value (true or false). If the condition is true, the code inside the if block statement will be executed; if the condition is false, the code inside the else block will be executed.

Let's demonstrates the use of if...else statement with an example below:

let age = 30; if (age >= 20) 
{ console.log("You are an adult."); } 
else { console.log("You are a minor."); }

In this example, the if statement checks whether the age variable is greater than or equal to 20. If it is true, the code inside the first block (i.e., "You are an adult.") will be executed. If it's false, the code inside the else block (i.e., "You are a minor.") will be executed.

The above example is a single if-else but you can also chain multiple if...else statements together to check for multiple conditions. Let's demonstrate with this example:

let grade = 70; if (grade >= 90) { console.log("You got an A."); } 
else if (grade >= 80) { console.log("You got a B."); } 
else if (grade >= 70) { console.log("You got a C."); } 
else if (grade >= 60) { console.log("You got a D."); } 
else { console.log("You failed."); }

In this example, the code checks the value of the grade variable and prints a message based on the grade. If the grade is greater than or equal to 90, it prints "You got an A." If it's greater than or equal to 80, it prints "You got a B." And so on, until it gets to the else block, which prints "You failed."

Last updated