JavaScript if else Tutorial

JavaScript Conditional Statements

We use conditional statements to perform different actions for different decisions. In JavaScript, we have the following conditional statements.

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use a switch to specify many alternative blocks of code to be executed

The if Statement

You can use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

if (condition) {
    a block of code to be executed if the condition is true
}

Example

If the marks of the student are more than 33 result will be passed.

if (marks > 33) {
    result = “pass”;
}

The result will be:

Pass

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

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

Example

If the marks of the student are more than 33 result will be pass or less than 33 fail.

if (marks > 33) {
    result = “pass”;
}

else {
     result = “fail”;
}

The result will be:

Fail

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
    block of code to be executed if condition1 is true
} else if (condition2) {
    
block of code to be executed if condition1 is false and condition2 is true
} else {
    
block of code to be executed if condition1 is false and condition2 is false
}

Example:

Take Your Free Live Demo Class Now

We Will Call Back You Shortly

Enter Your DETAILS BELOW

We Will Send You the Course Fees Details In Below Number

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

Enter Your DETAILS BELOW TO take

free demo class