Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 799
Jacob Morrison Avatar asked Jul 30 '13 15:07

Jacob Morrison


2 Answers

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.

like image 153
Rocket Hazmat Avatar answered Oct 25 '22 10:10

Rocket Hazmat


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.

like image 36
Barmar Avatar answered Oct 25 '22 10:10

Barmar