I was just trying this JS code -
if(a){
console.log("a IS DEFINED")
} else {
console.log("a IS UNDEFINED")
}
and I am getting error -
ReferenceError: a is not defined
But when I add var a it prints a IS UNDEFINED
var a;
if(a){
console.log("a IS DEFINED")
} else {
console.log("a IS UNDEFINED")
}
// prints a IS UNDEFINED
Why it behaves differently where in both case a is undefined?
Your confusion is completely understandable: It's two different uses of the word "undefined."
There's a difference between an undefined identifier and the value, undefined.
When you do
if (a)
...you're trying to take the value of the identifier a. If you haven't defined that identifier at all, it's a ReferenceError. The JavaScript engine has no idea whatsoever what a is meant to be.
In contrast, this:
var a;
defines the identifier (as a variable) and gives it the initial value undefined. So then when you do
if (a)
...the JavaScript engine knows what you're talking about: It goes to the variable a and gets its value.
If for some reason you need to know if an identifier is defined and you don't want to catch the error, you're allowed to take the type of an undefined identifier:
if (typeof a === "undefined")
That works (without an error) even if a is completely undefined. However, it doesn't make any distinction between the two things (an undefined identifier, and a defined identifier with an undefined value).
Now, as if this weren't confusing enough, in "loose mode" JavaScript has a very strange behavior I call The Horror of Implicit Globals: If you assign to an undefined identifier (instead of trying to read its value), instead of giving a ReferenceError, it creates a new global variable. Thankfully, we now have ES5's "strict mode" which makes doing that the error it always should have been. :-)
I would recommend you to use:
if (typeof a === 'undefined') {
console.log('a IS UNDEFINED');
} else {
console.log('a IS DEFINED');
}
A variable has the type of undefined if it hasn't a value or if it wasn't declared before.
In short, when you don't declare a variable but using it inside your code, it gets a ReferenceError as the variable you are pointing to cannot be referred.But when you declare the variable but don't initialize it,then the value isn't defined.
Example :
First Case :
if(j){
//do something
}
didn't declare j, but referring to it.So it'll give an undefined error because of not getting j as a declared/known variable.
Second Case :
var j;
if(j){
//do something
}
Here j==null will be true, but if(j) will be equivalent to if(null) that is same as if(false), not because j is null. Rather because j is undefined.
Related
Playing with javascript closures I end up with this question I cannot reach to explain.
(function() {
console.log("Inside closure"); //does not work
}(foo));
It does not work because foo is undefined. referenceError
But if prior I set var foo = undefined; it works (tested on Chrome and ff).
It is not the same to be undefined that to be set to undefined?
example in jsfiddle
In javaScript, 'undefined' is one of the primitive data types. It represents the type of an object.
var a = undefined;
var b;
console.log((typeof(a)));
console.log((typeOf(b)));
The output will be undefined for both the cases.
If you don't declare a variable at all and try to access it, the error thrown will be the following. I tried to access c which is not declared at all.
Uncaught ReferenceError: c is not defined(…)
Having a variable whose value is undefined is not the same as having no variable with that name.
In ECMAScript, identifiers are resolved according to Identifier Resolution, which returns a reference given by GetIdentifierReference.
In case the variable doesn't exist, the base value of that reference will be undefined, otherwise it will be an environment record.
When GetValue gets the value of that reference, it will check IsUnresolvableReference. If the base value is undefined, it will return false, and GetValue will throw a ReferenceError exception.
If the variable exists (even if its value is undefined), GetValue will return its value.
If you are not sure whether some variable exists, you can use the typeof operator, which returns "undefined" for unresolvable references instead of throwing.
If the question is:
But what if somebody uses the the common jQuery wrapper and has the jQuery script not working yet?
Then you will still get a reference error if the jQuery identifier is not in the global scope because it is trying to find the reference to jQuery but it will not exist.
the undefined keyword is passed in the closure so that if undefined is assigned a value, it will not mess with your code. For example:
var undefined = 123
if(undefined){
console.log("pass")
}
this code will pass. If you Pass through undefined but leave out the parameter when you invoke it, undefined will have not a value assigned to it. It wont be looking for a reference as you haven't assigned the parameter For example :
(function(undefined){
// undefined will be undefined.
}())
I've done a quick example here for you : https://jsfiddle.net/gn7h3641/
TLDR : if your asking JavaScript for the value of a variable that doesn't exist(not been defined with var), it will explode because it has not got a reference to find the value yet which is different to checking if something is undefined in a 'if(test === undefined)'
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.
Global Variables: typeof variable === "undefined"
Local Variables: variable === undefined
Properties: object.prop === undefined
Why does jQuery use one approach for global variables and another for locals and properties?
For undeclared variables, typeof foo will return the string literal "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.
Yet another reason for using the typeof-variant: undefined can be redefined.
undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
The result of typeof variable cannot.
Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:
15.1.1 Value Properties of the Global Object
[...]
15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes
{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
But it still can be shadowed by a local variable:
(function() {
var undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})()
or parameter:
(function(undefined) {
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})("foo")
Who is interested in the performance gain of variable === undefined, may take a look here, but it seems to be a chrome optimization only.
http://jsperf.com/type-of-undefined-vs-undefined/30
http://jsperf.com/type-of-undefined-vs-undefined
Because undefined is not always declared, but jQuery declares undefined in its main function. So they use the safe undefined value internally, but outside, they use the typeof style to be safe.
For local variables, checking with localVar === undefined will work because they must have been defined somewhere within the local scope or they will not be considered local.
For variables which are not local and not defined anywhere, the check someVar === undefined will throw exception: Uncaught ReferenceError: j is not defined
Here is some code which will clarify what I am saying above. Please pay attention to inline comments for further clarity.
function f (x) {
if (x === undefined) console.log('x is undefined [x === undefined].');
else console.log('x is not undefined [x === undefined.]');
if (typeof(x) === 'undefined') console.log('x is undefined [typeof(x) === \'undefined\'].');
else console.log('x is not undefined [typeof(x) === \'undefined\'].');
// This will throw exception because what the hell is j? It is nowhere to be found.
try
{
if (j === undefined) console.log('j is undefined [j === undefined].');
else console.log('j is not undefined [j === undefined].');
}
catch(e){console.log('Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.');}
// However this will not throw exception
if (typeof j === 'undefined') console.log('j is undefined (typeof(x) === \'undefined\'). We can use this check even though j is nowhere to be found in our source code and it will not throw.');
else console.log('j is not undefined [typeof(x) === \'undefined\'].');
};
If we call the above code like this:
f();
The output would be this:
x is undefined [x === undefined].
x is undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
If we call the above code like these (with any value actually):
f(null);
f(1);
The output will be:
x is not undefined [x === undefined].
x is not undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
When you do the check like this: typeof x === 'undefined', you are essentially asking this: Please check if the variable x exists (has been defined) somewhere in the source code. (more or less). If you know C# or Java, this type of check is never done because if it does not exist, it will not compile.
<== Fiddle Me ==>
Summary:
When at global scope we actually want to return true if the variable is not declared or has the value undefined:
var globalVar1;
// This variable is declared, but not defined and thus has the value undefined
console.log(globalVar1 === undefined);
// This variable is not declared and thus will throw a referenceError
console.log(globalVar2 === undefined);
Because in global scope we are not 100% sure if a variable is declared this might give us a referenceError. When we use the typeof operator on the unknown variable we are not getting this issue when the variable is not declared:
var globalVar1;
console.log(typeof globalVar1 === 'undefined');
console.log(typeof globalVar2 === 'undefined');
This is due to the fact that the typeof operator returns the string undefined when a variable is not declared or currently hold the value undefined which is exactly what we want.
With local variables we don't have this problem because we know beforehand that this variable will exist. We can simply look in the respective function if the variable is present.
With object properties we don't have this problem because when we try to lookup an object property which does not exist we also get the value undefined
var obj = {};
console.log(obj.myProp === undefined);
jQuery probably expects you to be using let and const variables in functions going forward, which in JavaScript's ES6 2015 design do NOT allow you to use any local scope (function) let or const variables until they are declared. Even hoisting by Javascript does not allow you to even type-check them!
If you try and do that, JavaScript generates an error, unlike with var variables which when hoisted creates a declared but uninitialized variable you can type check or check to see if its undefined.
If you declare a let or const variable in a function, but AFTER trying to access it, typeof checks still create a Reference Error in JavaScript! Its very odd behavior, and illogical to me why it was designed that way. But that is why jQuery likely sees no use for typeof function variable use. Example:
function MyError(){
// WOW! This variable DOES NOT EVEN EXIST, but you can still check its type!
if(typeof x === 'undefined')
{
alert(1);// OK!
}
// ERROR!
// WOW! You cannot even check an existing "let" variable's TYPE in a local function!
if(typeof y === 'undefined')//REFERENCE ERROR!!
{
alert(2);
}
// We defined the variable so its hoisted to the top but in a dead zone
let y = 'test';
}
MyError();
// RESULT
// alert 1 fires but a REFERENCE ERROR is generated from the second alert 2 condition.
It is odd above how a non-existing local variable cant be checked using typeof for 'undefined', but a declared let variable in the function cannot! So this is likely why I would not depend on jQuery to define what is best. There are edge cases.
More Weirdness on "undefined" variables in JavaScript
**undefined has two different expressions, and three different uses, as follows:
"typeof" and "undefined" types : Variables that are not declared and do not exist are not assigned anything, but have a "type" of undefined. If you access a variable that does NOT even exist, much less declared or initialized, you will generate a REFERENCE ERROR if you access it, even when testing for the primitive default value of undefined which is assigned to declared variables until assigned a value. So checking the "typeof" prevents this error in this one case as follows:
// In this first test, the variable "myVariable1" does not exist yet so creates
// an error if we try and check if its assigned the default value of undefined!
if (myVariable1 === undefined) alert(true);// REFERENCE ERROR!
// Here we can elegantly catch the "undefined" type
// of the missing variable and stop the REFERENCE ERROR using "typeof".
if (typeof myVariable1 === "undefined") alert(true);// true
// Here we have declared the missing variable and notice its
// still an "undefined" type until initialized with a value.
let myVariable1;
if (typeof myVariable1 === "undefined") alert(true);// true
// Lastly, after we assign a value, the type is no longer
// "undefined" so returns false.
myVariable1 = 'hello';
if (typeof myVariable1 === "undefined") alert(true);// false
All objects and types in JavaScript that are accessed but not declared will default to a type of "undefined". So, the lesson here is try and check for the typeof first, to prevent missing variable errors!
undefined primitive values : All declared variables not yet assigned a value are assigned in JavaScript the primitve of undefined. If you have declared a variable, but not initialized it yet, its assigned this default primitive type of undefined. That is not same as an "undefined" type. The primitive value of undefined is a reserved value but can be altered, but that's not what is asked here. Notice this catches all declared but uninitialized variables only:
let myVariable3;
if (myVariable3 === undefined) alert(true);// true
let myVariable4 = 'hello';
if (myVariable4 === undefined) alert(true);// false
Objects and undefined primitives : Lastly, Object properties do NOT behave like variables in JavaScript. Object properties, when missing do not become undefined types, but are simply assigned the primitive undefined as above for undeclared variables. So they act like #2:
let myObject = {};
if (myObject.myProperty === undefined) alert(true);// true
BEST PRACTICE
Lastly....this is a VERY GOOD REASON to always check for BOTH the "undefined" type and the undefined primitive value on variables in all your JavaScript code. Most will say, you will rarely need both. There may come a day when a missing variable is accessed in a library that does not exist and creates a nasty JavaScript REFERENCE ERROR! So I always do this check, and in this order, to stop all errors in JavaScript:
if (typeof myVariable !== "undefined" && myVariable !== undefined) {
// do something safe with myVariable!
}
typeof a === 'undefined' is faster then a === 'undefined' by about 2 times on node v6.9.1.
Recently, I've been learning JavaScript. I'm coming across a few JavaScript errors that say "__ is undefined" - What exactly does this mean, and why is this coming up? I'm looking more or less for an explanation on why this error is occurring and what can be done to fix it, or why it's generally occurring in the first place.
For example: Here are two functions (validate and onSearch) --- When I try to run "onSearch", I get the Ran SEARCH... trace in the console, however it disappears. Additionally, when I run it through JSHero (trying to debug), it tells me that "onSearch" is undefined, and I'm curious as to why.
I've go some experience developing with ActionScript, but I'm totally new to JavaScript. I'd really appreciate your input and explanation regarding what this actually means. Thanks you.
function validate(query){
console.log("Ran VALIDATE...");
// Trim whitespace from start and end of search query
while(query.charAt(0) === " "){
query = query.substring(1, query.length);
};
while(query.charAt(query.length-1) === ""){
query = query.substring(0, query.length-1);
};
console.log("Query length:",query.length);
console.log("Beginning conditional...");
// Check search length, must have 3 characters
if(query.length < 3){
console.log("Display alert...");
alert("Your search query is too small, try again.");
// (DO NOT FIX THE LINE DIRECTLY BELOW)
searchInput.focus();
}else{
console.log("Searching query...");
onSearch(query);
};
};
// Finds search matches
function onSearch(query){
//var search = function(query){
console.log("Ran SEARCH...");
// split the user's search query string into an array
var queryArray = query.join(" ");
// array to store matched results from database.js
var results = [];
// loop through each index of db array
for(var i=0, j=db.length; i<j; i++){
// each db[i] is a single video item, each title ends with a pipe "|"
// save a lowercase variable of the video title
var dbTitleEnd = db[i].indexOf('|');
var dbitem = db[i].tolowercase().substring(0, dbTitleEnd);
// loop through the user's search query words
// save a lowercase variable of the search keyword
for(var ii=0, jj=queryArray.length; ii<jj; ii++){
var qitem = queryArray[ii].tolowercase();
// is the keyword anywhere in the video title?
// If a match is found, push full db[i] into results array
var compare = dbitem.indexOf(qitem);
console.log("Compare:",compare);
if(compare != -1){
results.push(db[i]);
};
};
};
console.log("Hello");
results.sort();
// Check that matches were found, and run output functions
if(results.length === 0){
noMatch();
}else{
showMatches(results);
};
};
EDIT**
"db" is defined in an external file. It's just an array of URL's. It's still saying it's not defined as well, which is what I'm asking.
How do you define
1) A variable
2) A function
If you get a TypeError along the lines "Blah is undefined" or "cannot read property foo of undefined", it means that you have a variable or property that has the value undefined, which is the default value for a variable until you assign something to it.
This is as opposed to having a variable you haven't defined yet and trying to read its value, which will fire a ReferenceError instead.
For instance, consider the below:
var foo;
console.log(foo.bar); // "TypeError: Cannot read property 'bar' of undefined"
The foo variable exists, but its value is undefined, so trying to read a property from it causes an error.
Contrast that to:
console.log(missing); // "ReferenceError: missing is not defined"
Here, the symbol missing is not defined; the engine has no idea what you're talking about. This usually indicates a missing var statement.
Side note: JavaScript has a very surprising behavior if you assign to a variable you've never declared (in ES3 or in ES5 in "loose" mode): It creates a global variable. I call this The Horror of Implicit Globals. It means that if instead of console.log(missing); above, I did this:
missing = "foo";
...I'd be creating a new global variable, even if that code is within a function. Thankfully, in ES5, we can use "strict" mode, which makes this the ReferenceError it always should have been. :-)
It usually means that the 'thing' you're requesting does not exist(or atleast can't be found by the function requesting it). This can be a variable, object or a function.
In the case of the onSearch you're talking about is that the function can't be found, most likely. It could be that the file with the function in it is loaded after the file requests it(So onSearch is in b.js, the one requesting it is in a.js. a.js is in your <head> before b.js). Therefore it's not yet present, since javascript files load linear.
Your problem
The problem is not that onSearch is undefined, but it uses a variable db which is undefined.
Cases
(From now on I will assume qwertyuiopasddsghjdsvjkfhjkl is not declared)
You see undefined errors when:
You use variable you have not declared.
qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
You use a property on a declared but undefined variable:
var a;
a.b; // TypeError: a is undefined
A variable is undefined when:
(Error) You have not declared it
// qwertyuiopasddsghjdsvjkfhjkl is undefined
qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
(No error) You have declared it but it has no value
var a; //a is undefined
(No error) You assign a variable to void(0) (you can change 0 with everything) or and unmodified undefined
var a = undefined; //a is undefined
var a = void(0); //a is undefined
undefined = 'abc';
var a = undefined; //a is NOT undefined
How to check
If you don't know if a variable is undefined, you can use
typeof myVar === 'undefined'
It returns true if:
myVar is not declared
myVar is declared but is undefined
It returns false if myVar is declared and myVar is not undefined
myVar === void(0)
It returns true if myVar is declared and myVar is undefined
It returns false if myVar is declared and myVar is not undefined
It throws an error if myVar is not declared
myVar === undefined
It's the same as myVar === void(0) if undefined has not been modified.
!myVar, if(myVar)
It returns true if myVar is declared and
myVar is undefined
or
myVar is falsy (null, 0, false, '')
It returns false if myVar is declared and myVar is truthy
It throws an error if myVar is not declared
Everything I've ever read indicates that in Javascript, the boolean value of an undefined variable is False. I've used code like this hundreds of times:
if (!elem) {
...
}
with the intent that if "elem" is undefined, the code in the block will execute. It usually works, but on occasion the browser will throw an error complaining about the undefined reference. This seems so basic, but I can't find the answer.
Is it that there's a difference between a variable that has not been defined and one that has been defined but which has a value of undefined? That seems completely unintuitive.
What is a ReferenceError?
As defined by ECMAScript 5, a ReferenceError indicates that an invalid reference has been detected. That doesn't say much by itself, so let's dig a little deeper.
Leaving aside strict mode, a ReferenceError occurs when the scripting engine is instructed to get the value of a reference that it cannot resolve the base value for:
A Reference is a resolved name binding. A Reference consists of three
components, the base value, the referenced name and the Boolean valued
strict reference flag. The base value is either undefined, an Object,
a Boolean, a String, a Number, or an environment record (10.2.1). A
base value of undefined indicates that the reference could not be
resolved to a binding. The referenced name is a String.
When we are referencing a property, the base value is the object whose property we are referencing. When we are referencing a variable, the base value is unique for each execution context and it's called an environment record. When we reference something that is neither a property of the base object value nor a variable of the base environment record value, a ReferenceError occurs.
Consider what happens when you type foo in the console when no such variable exists: you get a ReferenceError because the base value is not resolvable. However, if you do var foo; foo.bar then you get a TypeError instead of a ReferenceError -- a subtle perhaps but very significant difference. This is because the base value was successfully resolved; however, it was of type undefined, and undefined does not have a property bar.
Guarding against ReferenceError
From the above it follows that to catch a ReferenceError before it occurs you have to make sure that the base value is resolvable. So if you want to check if foo is resolvable, do
if(this.foo) //...
In the global context, this equals the window object so doing if (window.foo) is equivalent. In other execution contexts it does not make as much sense to use such a check because by definition it's an execution context your own code has created -- so you should be aware of which variables exist and which do not.
Checking for undefined works for variables that have no value associated but if the variable itself hasn't been declared you can run into these reference issues.
if (typeof elem === "undefined")
This is a far better check as doesn't run the risk of the reference issue as typeof isn't a method but a keyword within JavaScript.
Is it that there's a difference between a variable that has not been defined and one that has been defined but which has a value of undefined?
Yes. A undeclared variable will throw a ReferenceError when used in an expression, which is what you're seeing.
if (x) { // error, x is undeclared
}
Compared to;
var y; // alert(y === undefined); // true
if (y) { // false, but no error
}
That seems completely unintuitive.
Meh... what I find unintuitive:
if (y) // error, y is undeclared
var x = {};
if (x.someUndeclaredAttribute) // no error... someUndeclaredAttribute is implictly undefined.
Here's an example of Jon's explanation regarding environment records:
var bar = function bar() {
if (!b) { // will throw a reference error.
}
},
foo = function foo() {
var a = false;
if (a) {
var b = true;
}
if (!b) { // will not throw a reference error.
}
};
In strict mode, it is an error:
function a() {
"use strict";
if (!banana) alert("no banana"); // throws error
}
It's always really been better to make an explicit test for globals:
if (!window['banana']) alert("no banana");
It doesn't make sense to perform such a test for non-global variables. (That is, testing to see whether the variable is defined that way; it's fine to test to see whether a defined variable has a truthy value.)
edit I'll soften that to say that it rarely makes sense to thusly test for the existence of non-globals.
When a variable is declared and not initialized or it's used with declaration, its value is "undefined". The browser complains exactly when this undefined variable is referenced. Here "reference" means some piece of javascript code is trying to visit an attribute or method of it. For example, if "elem" is undefined, this will throw an exception:
elem.id = "BadElem";
or you use try/catch:
try { x } catch(err){}
This way you're not doing anything in case of an error but at least your script won't jump off the cliff...
undefined = variable exists but has no value in it
ReferenceError = variable does not exist
Is there anything wrong with this test for undefined?
var undefined;
if(x == undefined){
//do something
}
or this:
function undefined(x){
return typeof x == 'undefined';
}
if(undefined(x)){
//do something
}
jsLint doesn't throws a reserverd word error, but the code still seems to work...
Don't redefine undefined.
Other programmers expect undefined to always be undefined, not a function for function's sake.
People often use typeof operator to ensure a reference error is not thrown when used to test for variables that are undefined.
If anyone ever does this to you, you can use...
undefined = void 0;
... to revert it back.
As undefined isn't a Javascript keyword, there's nothing wrong with it per se.
However, you're overriding a core variable that's used frequently for checking undefined variables in your second example to be a function. I'd shriek and ban that person as a committer if I saw that in anyone's code that I was reviewing.
undefined is just a default property of the global object, which you can override/redefine. That's why you should always test for undefined using typeof x == 'undefined', since the typeof operator cannot be redefined.
var undefined;
if(x == undefined){
//do something
}
What happening here is that you're defining a new variable called "undefined", which you don't assign a value and which hence gets the valued undefined. x is not defined either and also has a value of undefined. Hence both are equal. It's rather pointless though.
undefined is not a reserved word in JavaScript (ECMA-262).
It is a named constant of type Undefined;
By declaring:
var undefined;
you declare variable with the same name in local scope.
So technically you can do this, just don't define something like this:
var undefined = 13;