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'...
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.
The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.
'==' 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With