1

Say I have a conditional like this:

if (conditionOne && conditionTwo) { 
  // execute some code
}

If conditionOne is false, does that prevent computing conditionTwo? In many cases I don't want to compute conditionTwo because it would throw an error if conditionOne is false. For example, often times I want to make sure a particular property exists before I do anything with it. In the past I've used nested conditionals, but the && would save space and look cleaner in a lot of cases. I just want to make sure the second contrition will be left alone if the first is false.

Glenn
  • 4,195
  • 9
  • 33
  • 41
  • 2
    *If conditionOne is false, does that prevent computing conditionTwo?* **Yes**. – gurvinder372 Jan 23 '18 at 05:45
  • Another duplicate here: [Does Javascript have short circuit evalution](https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation) – jfriend00 Jan 23 '18 at 05:50

2 Answers2

1

If conditionOne is false, does that prevent computing conditionTwo?

Yes, it does. This is referred to as short circuiting.

A common idom in Javascript is exactly what you are discussing:

if (obj && obj.method) {
   obj.method();
}

If obj is not truthy, then obj.method will not be evaluated.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Yes. All the logical operators in ECMAScript short circuit.

'use strict';

function test(arg) {
  console.log(arg);
  return arg === 'true';
}

if (test('false') && test('true')) {
  console.log('Inside && if\'s body');
}

if (test('true') || test('false')) {
  console.log('Inside || if\'s body');
}

Output

false
true
Inside || if's body

In the &&'s if case, the first condition itself is failing. So the second one is not executed.

In the ||'s if case, the first condition itself is successful. So the second one is not executed.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497