DEV Community

GaurangDhorda
GaurangDhorda

Posted on

Multiple conditions with logical || operator

Order of condition matters because of short-circuit-evaluation. When we apply conditions with logical || or-operator, order of condition checking starts from left to right and if one of the condition that is... left or right condition of logical || is true then other is condition will not be checked.

Logical || or-operator with multiple conditions sets then, whenever there is only one condition becomes true after that rest of conditions checks gets break and gives output to only from one of the true condition. Condition checking starts from left to right order.

What is printed in console?

let car = () => {
  console.log('Audi - A4');
  return false;
};

let carManufacturer = () => {
  console.log('Audi Motors India Ltd.');
  return true;
}

let carOrManufaturerOne = false || car() || carManufacturer();
let carOrManufaturerTwo = false || carManufacturer() || car();
let carOrManufaturerThree = true || carManufacturer() || car();

Enter fullscreen mode Exit fullscreen mode
Answer of carOrManufaturerOne: 
   'Audi - A4',
   'Audi Motors India Ltd.'

// Because... carMenufaturer() is returned true, and is called lastly in condition chain.

Answer of carOrManufacturerTwo:
   'Audi Motors India Ltd.'

// Because... carMenufaturer() is returned true, and is called Second in condition chain. and then after all condition checks fails to laod.

Answer of carOrManufacturerThree:
   'nothing displayed on console.' or 'undefined'

// Because... First condition is returned true, and rest in condition chain fails to load. 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)