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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With