if else statement

The if else statement is an extended version of the if condition. It allows you to write code for both the cases i.e. either the expression returns true or false, you can handle both of them. The if statement will run for the true value while else for the false value.

Syntax:

if (conditional_expression){
// Code statements for true expression evaluation
}
else{
// Code statements for false expression evaluation
}

Example: The below code will explain the use of the if else statement in JavaScript.

Javascript
const num1 = 45;
const num2 = 8;

if(num1 < 50){
    console.log(`${num1} is less than 50`);
}
else{
    console.log(`${num1} is greater than 50`);
}

if(num1%num2 === 0){
    console.log(`${num2} completely divides ${num1}`);
}
else{
    console.log(`${num1} is not divisible by ${num2}`);
}

Output
45 is less than 50
45 is not divisible by 8

JavaScript if else else if

The if…else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed. This structure facilitates decision-making in JavaScript programs.

We have the following conditional statements available in JavaScript:

Table of Content

  • if statement
  • if else statement
  • else if statement

Similar Reads

if statement

The if statement is defined using the if keyword and is always operated with an expression passed inside the round brackets just after its definition....

if else statement

The if else statement is an extended version of the if condition. It allows you to write code for both the cases i.e. either the expression returns true or false, you can handle both of them. The if statement will run for the true value while else for the false value....

else if statement

The else if statement is used in the cases where you need to execute multiple code blocks based on multiple conditional expression. It starts with the if statement and ends with the else statement, it is written in between them....

Contact Us