最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - checking a variable value using an OR operator - Stack Overflow

programmeradmin2浏览0评论

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

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

Which is obviously not going to do what he intended, which was this:

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

But what I can't explain is why exactly the first snippet of code wouldn't work! Or why it evaluates to true if 'status' is set to 'incomplete' but to false when it's set to 'unknown'...

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

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

Which is obviously not going to do what he intended, which was this:

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

But what I can't explain is why exactly the first snippet of code wouldn't work! Or why it evaluates to true if 'status' is set to 'incomplete' but to false when it's set to 'unknown'...

Share Improve this question asked Mar 11, 2013 at 16:20 molokomoloko 4784 silver badges9 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 21

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.

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

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)

  1. 暂无评论