Recently came across short-circuit evaluation and was a little confused by it as i only got into programming the past week. From what i understand if what ever comes before the first double pipe is true then it will stop and not evaluate what comes after the double pipe. For Example:
Example 1:
var a = true;
var b = a || {};
So i assume if a exists then assign a to b otherwise b is equal to an object. What i dont understand is where i will use this and how it differs to a ternary operator, isn't the short circuit evaluation the same as:
Example 2:
var a = true;
var b = (a) ? a : {};
Why would one use example 1 over example 2 as it isn't any slower to write out or is there a speed benefit of the use of one over the other? or is this just a silly question and perhaps i'm missing something. If someone could clear this up for me that would be great.
Both of your examples will result in b
being assigned the value of a
(true
), and both constructs avoid the evaluation of the final operand (which is {}
in each case).
However, there are differences in readability and evaluation.
Readability:
I'd argue that if (a || b) { ... }
is more readable than if (a ? a : b) { ... }
).
Operand evaluation:
In (a || b)
, a
is only evaluated once. In (a ? a : b)
, a
is evaluated twice. This becomes important when instead of a simple variable you are using an function or other expression:
// Costly double evaluation
var a = someExpensiveFunction()
? someExpensiveFunction()
: {};
// Less costly single evaluation
var a = someExpensiveFunction() || {};
More generally, short circuit operators can help you:
var a = a && someFunctionThatWillThrowIfAIsNull(a);
// Slower
var a = someSlowFunction() || someFastFunction();
// Faster
var a = someFastFunction() || someSlowFunction();