0

Given these two functions in JavaScript:

function (){
  return _.includes(someLongArray, value) && someSimpleValue;
}

VS

function (){
  return someSimpleValue && _.includes(someLongArray, value);
}

Which of those is going to have better performance? When the someSimpleValue is false, is it going to call the return automatically? Or is it going to verify if the second one is true or false (Useless cause when a && has some of them false it can't be truthy anymore)

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Alejandro Vales
  • 2,816
  • 22
  • 41

3 Answers3

5

The second is more efficient because using the '&&' operator will short-circuit if the first condition evaluates to false.

Further reading/duplicate:

Does JavaScript have "Short-circuit" evaluation?

Community
  • 1
  • 1
lintmouse
  • 5,079
  • 8
  • 38
  • 54
2

The second is faster

When using the && operator javascript checks the left side, if it's true checks the right side - if it's false it doesn't check the right side.

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

false && (anything) is short-circuit evaluated to false. true || (anything) is short-circuit evaluated to true.

full article

Elheni Mokhles
  • 3,801
  • 2
  • 12
  • 17
0

The second one will be faster because of "short-circuit" and as soon as the first condition is false it "exits"