0

Does JavaScript operate the same as languages like C where if multiple conditionals are given, then the if statement when the entire thing can be guaranteed to be evaluated false/true?

I.E.

if( x == y || y == z)

or

if( x == y && y == z)

I know C doesn't check the second conditional in the first statement if the first conditional is evaluated true, as well as not checking the second conditional in the second statement is the first conditional is evaluated false.

I realize this is a quick Google, but I completely forgot what this compiler-level behavior is called and as a result was not able to find the answer.

Stephen Park
  • 13
  • 2
  • 6

4 Answers4

3

We can run a simple javascript test to see this in action.

function check(){
  console.log('called');
  return true;
}
let x = true, y = true;
if(x != y || x == check()){
  console.log('or verified');
}

if(x != y && x == check()){
  console.log('and verified');
}

Our console doesn't display and verified for our second if statement since it never runs.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
marvel308
  • 10,288
  • 1
  • 21
  • 32
0

What you are looking for is short circuit evaluation. Yes, javascript short circuits so that the second expression won't be evaluated if it doesn't need to be.

Mark
  • 9,718
  • 6
  • 29
  • 47
0

Yes. It's called short-circuit evaluation!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation

Slava Eremenko
  • 2,235
  • 1
  • 11
  • 9
0

Yes Javascript has it and the name is "short circuit evaluation" just like C. In fact I often use this to make sure I don't read a property from a object that doesn't exist.

For example:

return object && object.property

You can read more about this here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators