简体   繁体   中英

Difference between using a ternary operator or just short-circuit evaluation?

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.

There are several ways short circuit operators can affect correctness and performance.

The critical thing is avoiding side effects or performance hits of the second operand.

Short circuiting can avoid errors by only evaluating the second operand when it is safe:

var a = a && someFunctionThatWillThrowIfAIsNull(a);

A slow function can be avoided by placing it second if a faster function's result can make the second operand redundant:

var a = someFastFunction() || someSlowFunction();

Here is an example the different usages (depending on the first parameter). Check the console for each of them to understand the way they work.

 console.log("'' || {}:", '' || {}); console.log("1 || {}:", 1 || {}); console.log("0 || {}:", 0 || {}); console.log("true || {}:", true || {}); console.log("false || {}:", false || {}); console.log("[] || {}:", [] || {}); console.log(''); console.log("('') ? '' : {}:", ('') ? '' : {}); console.log("(1) ? 1 : {}:", (1) ? 1 : {}); console.log("(0) ? 0 : {}:", (0) ? 0 : {}); console.log("(true) ? true : {}:", (true) ? true : {}); console.log("(false) ? false : {}:", (false) ? false : {}); console.log("([]) ? [] : {}:", ([]) ? [] : {}); console.log(''); console.log("'' && {}:", '' && {}); console.log("1 && {}:", 1 && {}); console.log("0 && {}:", 0 && {}); console.log("true && {}:", true && {}); console.log("false && {}:", false && {}); console.log("[] && {}:", [] && {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM