Jacob Morrison
Jacob Morrison

Reputation: 648

'undefined' variable works as key to object with 'undefined' property name

Consider the following...

var x = {};
x.undefined = "Hello World!";
var y;

//Prints "Hello World!"
console.log(x[y]);

Working jsFiddle

Why does this happen? Is it because of this, where it is returning a string instead of the actual undefined?

Upvotes: 19

Views: 13377

Answers (3)

gen_Eric
gen_Eric

Reputation: 227200

When you do x.undefined you are setting a property of x called 'undefined'. The fact that it shares a name with undefined (a reserved word variable with writable:false) is coincidence.

Later on when you do, console.log(x[y]), you are looking for y in x. Keys of objects are strings, so y is converted to a string. When undefined is converted to a string, it becomes 'undefined'. That's why 'Hello World!' is returned.

Upvotes: 31

Barmar
Barmar

Reputation: 780724

When properties are accessed using . notation, the property name is not evaluated as an expression, it's a literal string.

x.undefined

is equivalent to:

x['undefined']

To set a property whose key is undefined, you would have to write:

x[undefined] = "Bye, cruel world";

Interestingly, Chrome lets me do this.

Upvotes: 8

fmgp
fmgp

Reputation: 1636

You define the "undefined" property for x, but you don't override the "undefined" property of global object

Upvotes: 0

Related Questions