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)
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.
To check a variable is null or not, we use is_null() function. A variable is considered to be NULL if it does not store any value. It returns TRUE if value of variable $var is NULL, otherwise, returns FALSE.
In JavaScript, null is a special value that represents an empty or unknown value. For example, let number = null; The code above suggests that the number variable is empty at the moment and may have a value later.
null and undefined both return false . That's why your code is actually checking if false is equal to false . However their types are not equal. Because of that, the next statement will return false, as the === comparison operator checks both the types and their value.
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 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