What is the mos reliable way if I want to check if the variable is null or is not present?.
There are diferent examples:
if (null == yourvar)
if (typeof yourvar != 'undefined')
if (undefined != yourvar)
What is the mos reliable way if I want to check if the variable is null or is not present?.
There are diferent examples:
if (null == yourvar)
if (typeof yourvar != 'undefined')
if (undefined != yourvar)
None of the above.
You don't want to use ==
, or a variety thereof, because it performs type coercion. If you really want to check whether something is explicitly null, use the ===
operator.
Then again, your question shows perhaps some lack of clarity of your requirements. Do you actually mean null
specifically; or does undefined
count too? myVar === null
will certainly tell you if the variable is null, which is the question you asked, but is this really what you want?
Note that there's a lot more information in this SO question. It's not a direct duplicate, but it covers very similar principles.
I prefer
if (null == yourvar)
which avoids the accidental assignment in this scenario
if (yourvar = null)
Edit
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
* Two strings are strictly equal when they have the same sequence of characters,
same length, and same characters in corresponding positions.
* Two numbers are strictly equal when they are numerically equal (have the
same number value). NaN is not equal to anything, including NaN.
Positive and negative zeros are equal to one another.
* Two Boolean operands are strictly equal if both are true or both are false.
* Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===)
Read Comparison Operators
"undefined" is not "null". Compare
some facts that can help you further
If you don't care if it's precisely null or undefined or false or 0, and just want to see if it's basically "unset", don't use an operator at all:
if (yourVar)
if (null == yourvar)
and
if (typeof yourvar != 'undefined')
do very different things. One assumes the variable exists, the other does. I would suggest not to mix the two at all. Know when to expect the variable deal with it's presence before you deal with its value.