Reputation: 648
Consider the following...
var x = {};
x.undefined = "Hello World!";
var y;
//Prints "Hello World!"
console.log(x[y]);
Why does this happen? Is it because of this, where it is returning a string instead of the actual undefined?
Upvotes: 19
Views: 13377
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
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
Reputation: 1636
You define the "undefined" property for x, but you don't override the "undefined" property of global object
Upvotes: 0