Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking a variable value using an OR operator

Tags:

javascript

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'...

like image 355
moloko Avatar asked Mar 11 '13 16:03

moloko


People also ask

How do you know if a variable is defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a variable contains a value in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.

Which operator is used to check both value and type in JavaScript?

'==' operator: In Javascript, the '==' operator is also known as loose equality operator which is mainly used to compare two value on both the sides and then return true or false. This operator checks equality only after converting both the values to a common type i.e type coercion.

How do you check if a variable is null in JavaScript?

Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.


1 Answers

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.

like image 113
Jeremy Roman Avatar answered Oct 18 '22 10:10

Jeremy Roman