JavaScript: undefined !== undefined?
It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined
when object.x is the real undefined. In my case I inadvertently set undefined to null.
The easiest way to see this happen is:
window.undefined = null;
alert(window.xyzw === undefined); // shows false
Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
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')
Javascript !undefined gives true?
Is this the expected behavior.
Yes.
If so then why ?Am I missing some concept/theory about undefined in Javascript?
JavaScript has the concept of implicit conversion of values (aka coercing values). When you use the negation ("NOT") operator (!
), the thing you're negating has to be a boolean, so it converts its argument to boolean if it's not boolean already. The rules for doing that are defined by the specification: Basically, if the value is undefined
, null
, ""
, 0
, 0n
, or NaN
(also document.all
on browsers¹), it coerces to false
; otherwise, it coerces to true
.
So !undefined
is true
because undefined
implicitly converts to false
, and then !
negates it.
Collectively, those values (and false
) are called falsy values. Anything else¹ is called a truthy value. This concept comes into play a lot, not just with !
, but with tests in if
s and loops and the handling of the return value of callbacks for certain built-in functions like Array.prototype.filter
, etc.
¹ document.all
on browsers is falsy, even though it's an object, and all (other) objects are truthy. If you're interested in the...interesting...history around that, check out Chapter 17 of my recent book JavaScript: The New Toys. Basically, it's to avoid sites unnecessarily using non-standard, out of date features.
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?
}
What is the difference between null and undefined in JavaScript?
undefined
means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows 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
.
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`");
}
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
In if statement,undefined equals with false
It means that undefined
is a falsy value, list of falsy values are:
"" // Empty string
null // null
undefined // undefined, which you get when doing: var a;
false // Boolean false
0 // Number 0
NaN // Not A Number eg: "a" * 2
If you negate a falsy value you will get true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
And when you nagate a truthy value you will get false:
!"hello" === false
!1 === false
But undefined
is not equal false
:
undefined === false // false
undefined == false // false
And just for the fun if it:
undefined == null // true
Related Topics
In iOS8 Using .Focus() Will Show Virtual Keyboard and Scroll Page After Touch
Preloader Wont Ignore Websocket - Pace Js
Encrypt iOS and Decrypt Node.Js Aes
Ckeditor 4: Uncaught Typeerror: Cannot Read Property 'Langentries' of Null
"Cannot Use Import Statement Outside a Module" Error When Importing React-Hook-Mousetrap in Next.Js
Is JSON Hijacking Still an Issue in Modern Browsers
Programming Language Independent Model Validation
How to Change the HTML Content as It's Loading on the Page
Es6 Template Literals VS. Concatenated Strings
Where Do the Parameters in a JavaScript Callback Function Come From
Why Does "True" == True Show False in JavaScript
Understanding Service Worker Scope
How to Display PDF (Blob) on iOS Sent from My Angularjs App
Are There JavaScript or Ruby Versions of "HTML Tidy"
What Are Asynchronous Functions in JavaScript? What Is "Async" and "Await" in JavaScript