Javascript if else

Learn how to handle the logical conditioning with if else in javascript.

Very often we need to execute our code based on different conditions. With if else we can handle this very easily in javascript. It starts the execution from the top and checks each condition provided.

Syntax

if(condition){
   //code to be executed
}

There may be cases when you need to evaluate multiple conditions to make your program work completely. In javascript we can do so with following methods.

if

Used to execute particular code when condition is true.

if(2 > 0){
  console.log('2 is greater than 0');
}

else

Used to execute particular code when condition is false.

if(2 > 0){
  console.log('2 is greater than 0');
}else{
  console.log('2 is not greater than 0');
}

else if

Used to execute particular code with multiple conditions.

let value = 2;

if(value > 0){
  console.log('2 is greater than 0');
}else if(value > 1){
  console.log('2 is greater than 1');
}else if(value >= 2){
  console.log('2 is greater than or equal 2');
}else{
  console.log('2 is less than 0');
}

We can use multiple else if condition.


We can omit the { } braces if we are using single if else in javascript.

//Executing only if
if(2 > 0)
  console.log('I will work');

//Executing if else
if(2 > 0)
  console.log('I will work');
else
  console.log('I will work as well');

But you should be careful using this syntax as this may result in error in some cases. Also you cannot use else if with this.


You can also check the value of functions.

We can conditionally check the functions directly inside the if else block.

//increment function
let add = (val) => {
  return val + 1;
}

if(add(10) === 11){
  console.log('We directly called the function');
}else{
  console.log('It is not getting incremented');
}

//We directly called the function

You can also use the switch statements to do logical conditioning.