[removed] Conditional (ternary) vs boolean OR for non-boolean values?

前端 未结 4 1987
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 23:16

In JavaScript, can I always use boolean OR instead of conditional operator for all kind of variables (e.g. string, function, ...)?

For example z = (x || y)

4条回答
  •  悲哀的现实
    2021-01-13 23:35

    They are similar, but are not quite the same. x ? x : y ends up evaluating x twice if x is chosen. This could cause an unexpected effect if x is a function call.

    You can find a formal proof of this in the ECMA specification.

    Another way to prove this:

    function a() { c++; return true; }
    function b() { d++; return true; }
    var c = 0, d = 0;
    a() || 3;
    b() ? b() : 3;
    /* c is 1; d is 2 */
    

提交回复
热议问题