How to check a not-defined variable in JavaScript
In JavaScript, null
is an object. There's another value for things that don't exist, undefined
. The DOM returns null
for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined
is the value used.
Second, no, there is not a direct equivalent. If you really want to check for specifically for null
, do:
if (yourvar === null) // Does not execute if yourvar is `undefined`
If you want to check if a variable exists, that can only be done with try
/catch
, since typeof
will treat an undeclared variable and a variable declared with the value of undefined
as equivalent.
But, to check if a variable is declared and is not undefined
:
if (yourvar !== undefined) // Any scope
Previously, it was necessary to use the typeof
operator to check for undefined safely, because it was possible to reassign undefined
just like a variable. The old way looked like this:
if (typeof yourvar !== 'undefined') // Any scope
The issue of undefined
being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use ===
and !==
to test for undefined
without using typeof
as undefined
has been read-only for some time.
If you want to know if a member exists independent but don't care what its value is:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
If you want to to know whether a variable is truthy:
if (yourvar)
Source
JavaScript check if variable exists (is defined/initialized)
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
How can I check for undefined in JavaScript?
If you are interested in finding out whether a variable has been declared regardless of its value, then using the in
operator is the safest way to go. Consider this example:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in
operator for a more robust check.
"theFu" in window; // true
"theFoo" in window; // false
If you are interested in knowing whether the variable hasn't been declared or has the value undefined
, then use the typeof
operator, which is guaranteed to return a string:
if (typeof myVar !== 'undefined')
Direct comparisons against undefined
are troublesome as undefined
can be overwritten.
window.undefined = "foo";
"foo" == undefined // true
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined
is non-writable.
if (window.myVar)
will also include these falsy values, so it's not very robust:
false
0
""
NaN
null
undefined
Thanks to @CMS for pointing out that your third case - if (myVariable)
can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError
.
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
How can I determine if a variable is 'undefined' or 'null'?
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
.
How to check for an undefined or null variable in JavaScript?
You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:value = obj.prop || defaultValue
which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
will evaluate to true
if value
is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specification at the ToBoolean
section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
How to check if a JavaScript variable is NOT undefined?
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Related Topics
Es6 Modules: Export Single Class of Static Methods or Multiple Individual Methods
How to Bind Fancybox to Dynamic Added Element
How to Find Events Bound on an Element with Jquery
How to Getelementbyclass Instead of Getelementbyid with JavaScript
How to Sort Array Inside Collection Record in Mongodb
Event Handlers Inside a JavaScript Loop - Need a Closure
Access Object Child Properties Using a Dot Notation String
Recurring Events in Fullcalendar
How to Edit a JavaScript Alert Box Title
How to Pass Data from a Page to Another Page Using React Router
How to Set the Value Property in Angularjs' Ng-Options
How to Check a Radio Button with Jquery
How to Use Namespaces with Typescript External Modules
Display Date/Time in User's Locale Format and Time Offset
Is There a More Accurate Way to Create a JavaScript Timer Than Settimeout