How do I determine if variable is undefined
or null
?
My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class'); if(EmpName == 'undefined'){ // DO SOMETHING };
<div id="esd-names"> <div id="name"></div> </div>
But if I do this, the JavaScript interpreter halts execution.
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 a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.
Difference Between undefined and nullundefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.
You can use the qualities of the abstract equality operator to do this:
if (variable == null){ // your code here. }
Because null == undefined
is true, the above code will catch both null
and undefined
.
The standard way to catch null
and undefined
simultaneously is this:
if (variable == null) { // do something }
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) { // do something }
When writing professional JS, it's taken for granted that type equality and the behavior of ==
vs ===
is understood. Therefore we use ==
and only compare to null
.
The comments suggesting the use of typeof
are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try
/catch
if you are working with the input you don't have control over.
You should not have any references to undeclared variables in your code.
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