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

前端 未结 4 1989
隐瞒了意图╮
隐瞒了意图╮ 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:51

    Those two expressions are equivalent in javascript because the logical "or" operator returns the first element if it's "true" or the second otherwise.

    However you should be careful about what values are true and what are instead considered false because this is different from other dynamically typed languages... for example both "" and 0 are false for Javascript and Python, but [] is false for Python but true for Javascript. In Common Lisp instead everything is considered "true" (including 0 or "" or an empty array) with the only exception of NIL that is considered false (NIL however is also the "empty list").

    Very useful is that undefined is considered "false" by Javascript, as this allows for example to write code like obj.redraw && obj.redraw(); that will call the redraw method only if it's present and doing nothing otherwise (a function/method is "true" for Javascript).

    If with x or y instead you don't mean actually variables but expressions then the two are not equivalent because x in the "ternary operator" version will be evaluated twice (if "true" on the first evaluation) and only once in the "logical or" version. This makes a difference if x is a function call.

    If you want to force a value to its boolean result for Javascript the most common idiom is probably !!x that is always true or false.

提交回复
热议问题