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?
}
Answer from Anurag on Stack Overflow[AskJS] Why doesn't JS deprecate undefined and replace everything with null?
language design - What exactly undefined means in JavaScript? Why it's there? What usages it has? How it could be useful? - Software Engineering Stack Exchange
Custom JavaScript Variable returns "undefined" every time
After Effects: Javascript - Undefined value used in the expression(Could be out of range array subscript)
Videos
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?
}
I personally use
myVar === undefined
Warning: Please note that === is used over == and that myVar has been previously declared (not defined).
I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)
Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"
Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?
If you follow this rule, good for you: you aren't a hypocrite.
The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can
window.setTimeout = function () {
alert("Got you now!");
};
Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.
(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)
Also, like the typeof approach, this technique can "detect" undeclared variables:
if (window.someVar === undefined) {
doSomething();
}
But both these techniques leak in their abstraction. I urge you not to use this or even
if (typeof myVar !== "undefined") {
doSomething();
}
Consider:
var iAmUndefined;
To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).
if ("myVar" in window) {
doSomething();
}
But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)
I never understood why JS makes a distinction between the two. Other programming languages don't have undefined and only have a null value.
I understand that they represent different things, but in practice they are used in exactly the same way. Accessing a property on an undefined/null value gives the same error Cannot read property x of undefined/null. I have never found it useful to make a distinction between the two and I usually have to always make double checks like if (x === undefined || x === null).
Was this just a poor design decision that is here to stay? If someone actually has a use case for knowing the distinction between null vs undefined, I would like to hear it.
There are two things you should understand about undefined:
- the type
undefinedthat can have only one value - the variable
undefined
To explain:
There are so many values of type
number(10, 10.01, 1e1). But there can be only one value of typeundefined, and that value is stored in the variableundefined.That value has no literal representation either. For example, number values
1,100,1e-1are all literals of type number, but the value stored in the variableundefinedhas no literal form.undefinedis a variable, just a normal variable, that JavaScript declares and assigns it the value of typeundefinedin the global scope. So you can do all the following...typeof undefined; // "undefined" undefined = 100; typeof undefined; // "number" undefined = void 0; typeof undefined; // "undefined" window.undefined === undefined; // true window.undefined === void 0; // trueif you don't want to use the variable
undefined, you can generate the value of typeundefinedby the expressionvoid 0-- whose sole purpose is to return a value of typeundefined.
...can anyone please explain to me why this thing has been inserted into JavaScript...
JavaScript has had a history of bad design - not because of the people who designed it but because no one could foresee that this little scripting capability they were adding to Netscape would one day underpin the business of billion dollar companies.
...we have null value...
Although null can do things undefined does, it is more or less related to objects rather than scalars. Indeed, JavaScript considers null itself an object -- typeof null returns "object".
Sorry for answering an older question but the reason you need both undefined and null is simple: in a prototype-based duck-typing language you absolutely must differentiate between "this object does not define a value for X" and "this object says X is nothing/null/empty".
Without this capability there is no way to walk the prototype chain and so inheritance can't work; you must be able to determine that obj.someProp is undefined so you can look at obj.prototype.someProp, and onward up the chain until you find a value. If obj.someProp returned null there would be no way to know if it really was null or just meant "look at my prototype". The only other way around this is to inject some kludgy magic behind the scenes which breaks your ability to fuzz with the prototype chains and do various other bits of JS black magic.
Like much of Javascript, the idea of undefined and null seems wonky and stupid at first, then absolutely brilliant later (then back to wonky and stupid but with a reasonable explanation).
A language like C# will not compile if you access a property that doesn't exist and other dynamic languages often throw exceptions at runtime when you touch a property that doesn't exist, meaning you have to use special constructs to test for them. Plus classes means when an object is instantiated you already know its inheritance chain and all the properties it has - in JS I can modify a prototype 15 steps up the chain and those changes will appear on existing objects.