checking a variable value using an OR operator

后端 未结 3 1562
野的像风
野的像风 2021-01-11 10:55

So, a junior programmer on my team today wrote the following piece of code:

if(status === (\"incomplete\" || \"unknown\"))

Which is obvious

相关标签:
3条回答
  • 2021-01-11 11:47

    In JavaScript, the || operator returns its first operand if it evaluates to true (i.e. it is not false, null, undefined, "", or 0), and its second operand otherwise.

    In the first case, ("incomplete" || "unknown") always evaluates to "incomplete", since it evaluates to true.

    The entire condition then becomes:

    if (status === "incomplete")
    

    Which explains the behaviour you are observing.

    0 讨论(0)
  • 2021-01-11 11:49

    ("incomplete" || "unknown") will return "incomplete" which is than compared to status.

    0 讨论(0)
  • 2021-01-11 11:51

    But what I can't explain is why exactly status === ("incomplete" || "unknown") wouldn't work

    That's because the expression in the parenthesis is evaluated first. The non-empty string incomplete is truthy, so the OR-expression ("incomplete" || "unknown") yields "incomplete" and only that is then compared with your status variable.

    To shorten the condition, there are many ways including arrays of values, regular expression test etc.

    0 讨论(0)
提交回复
热议问题