For undeclared variables, typeof foo will return the string "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".
For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.
Answer from Linus Kleen on Stack OverflowFor undeclared variables, typeof foo will return the string "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".
For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.
I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.
I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.] However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.
For example, the following is used in IE for parsing XML:
var x = new ActiveXObject("Microsoft.XMLDOM");
To check whether it has a loadXML method safely:
typeof x.loadXML === "undefined"; // Returns false
On the other hand:
x.loadXML === undefined; // Throws an error
UPDATE
Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to @LinusKleen for reminding me. For example:
typeof someUndeclaredVariable; // "undefined"
someUndeclaredVariable === undefined; // throws a ReferenceError
Bottom line: always use the typeof check.
Videos
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
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
An undeclared variable (that is, one that doesn't exist) does not have a type - and so its type is undefined. I believe that the generally accepted way to test if something is undefined is
typeof var === 'undefined'
rather than
var === undefined
since if the variable does not exist, you cannot access it. The latter case might be more useful if you are sure the variable should exist, since the difference between the two is that an undeclared variable will return false in the first case but cause an error in the second case.
Make sure that you use the triple-equals operator though if you're using the second variant; the (more usual) double-equals operator performs type coercion, so null == undefined is true while null === undefined is false. Sometimes you might want the first behaviour, though often you'll want the second, especially if you're testing against undefined, so it's important to recognise the difference. (This is another benefit of the first case since it's not possible to make this subtle error).
Yes, variables can have a value of undefined and you can explicitly assign values to them. Assigning undefined to a variable though is probably confusing, since it's a bit of a paradox (you've defined the variable as undefined) and it's not possible to distinguish that variable from either variables that don't exist or uninitialised variables. Use null if you want to signify that a variable has no value currently, or if you want to "undeclare" the variable altogether, use delete {varname}. Assigning undefined to a variable does not remove that variable's declaration; and it will still appear in the list of its owning object's properties if you iterate over them, so I can't think of any situation this would benefit you.
Edit: In response to the comment, when comparing the values with === (or ==), the variable must be deferenced to obtain its current value in order to do the comparison. Since the variable doesn't exist, this dereferencing fails (no real surprises so far). While you might expect the typeof operator to work in a similar way (get the current value, see what its type is) it specifically works with undefined variables. The "short version" (as used by the Mozilla reference ) is simply that "The typeof operator returns a string indicating the type of the unevaluated operand."
The long version, extracted from the ECMAScript spec, is that there's a special case for undefined variables:
11.4.3 typeof UnaryExpression is evaluated as follows:
- Evaluate UnaryExpression (as per 10.1.4 this returns "a value of type Reference whose base object is null and whose property name is the identifier" if the variable is undeclared).
- If Type(Result(1)) is not Reference, go to step 4. (It is a Reference)
- If GetBase(Result(1)) is null, return "undefined". (This is the special case matching undefined variables)
As for your comment to the first question, "how can you classify what does not exist" - it's easy! Simply divide all concepts into things that do exist (e.g. squirrel, rock) and those that don't exist (unicorns, warp drives). That's what undefined means; regardless of its semantics in English, its Javascript meaning is that the variable hasn't been declared or populated yet, and so while the concept of "a variable called foo" is valid, there exists no variable with that name holding a real value.
JavaScript provides several different notions of missing or empty variables (and object properties):
Variables that are actually 'not defined', i.e. they don't exists as a given name isn't bound in the current lexical environment. Accessing such a variable will throw an error, but using
typeofwon't and will return'undefined'. In contrast, accessing non-existing properties will not throw an error and returnundefinedinstead (and you may use theinoperator or thehasOwnProperty()method to check if properties actually do exist).Existing variables which have not been assigned a value (which is common because of var hoisting) or which have been explicitly set to
undefined. Accessing such a variable will returnundefined,typeofwill return'undefined'.Existing variables which have been explicitly set to
null. Accessing such a variable will returnnull,typeofwill return'object'. Note that this is misleading:nullis not an object, but a primitive value of type Null (which has the consequence that you can't returnnullfrom constructor functions - you have to throw an error instead to denote failure).
I'd recommend the following practices:
- Use
typeofto check forundefined, as it will cover the first two cases. - Don't assign
undefinedto properties: Usedeleteto get rid of them instead; note that you cannot delete variables (but also note that globals are actually properties of the global object and thus can be deleted). - Use
nullto mark the absence of a meaningful value (eg the forward reference of the last node of a linked list) or if you want to clear a variable as a hint to the garbage collector.
You could go with undefined for 3. as well and never use null at all.
The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:
typeof x == "undefined"
this ensures the type of the variable is really 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
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.