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?
}
Which is the better way to check undefined in Javascript?
There are various use case as following
if (variable)
is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN DocsThe cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned
undefined
.
In that case useif (variable !== undefined)
.If you are receiving response from an API which might consist of stringified value of
undefined
, which you are sure of, then only do the checkif (variable !== 'undefined')
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
.
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 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
Detecting an undefined object property
The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try to access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined
.
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
Check if variable is undefined
undefined is falsy in js...it looks like bar.baz may be your culprit.
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 - Can't check if variable is undefined
The obj
property is undefined. First, you need check variable
and the obj
property. After it you can access and check if variable.obj[0]
is undefined
.
Try:
if (variable && variable.obj && typeof variable.obj[0] === 'undefined'){
console.log("yes it's undefined !")
}
Related Topics
How to Sort an Object Array by Date Property
When Is .Then(Success, Fail) Considered an Antipattern For Promises
Merge/Flatten an Array of Arrays
How to Remove a Property from a JavaScript Object
Test For Existence of Nested JavaScript Object Key
How to Obfuscate (Protect) JavaScript
Why Do Regex Constructors Need to Be Double Escaped
How to Set/Unset a Cookie With Jquery
Preview an Image Before It Is Uploaded
How to Filter Object Array Based on Attributes
How to Create a File in Memory For User to Download, But Not Through Server
Is It Safe to Expose Firebase APIkey to the Public
Ways to Deal With #Document Under Iframe
Trigger a Button Click With JavaScript on the Enter Key in a Text Box