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

爱⌒轻易说出口 提交于 2019-11-29 16:08:20

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("[] && {}:", [] && {});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!