17

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?

Community
  • 1
  • 1
Jacob Morrison
  • 610
  • 2
  • 10
  • 19
  • The same trick works with x.true = "Hello World".. x.true and x['true'] are refer to the same value. – Mishax Jun 28 '15 at 07:34

3 Answers3

27

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
8

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 8
    In that last case, the key `undefined` is coerced to `"undefined"`, because [ECMAScript property access](http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.1) (see step 6) coerces the key to a string with [`ToString`](http://www.ecma-international.org/ecma-262/5.1/#sec-9.8), and `ToString(undefined) => "undefined"`. – apsillers Jul 30 '13 at 15:51
  • Yeah, I figured that out by calling `typeof` the key. – Barmar Jul 30 '13 at 15:52
  • @apsillers curious, is it just chrome that allows undefined or do all modern browsers conform to that spec – Melbourne2991 Feb 02 '16 at 04:54
  • @Melbourne2991 All JavaScript implementations should follow the ECMAScript specification. If a JavaScript engine doesn't follow the spec, it's not really JavaScript. (Of course, an implementation may be incomplete or have bugs in it, but spec conformance is the goal.) – apsillers Feb 02 '16 at 11:14
  • @apsillers's comment should be marked as the right answer! – morels Feb 22 '22 at 08:29
0

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

fmgp
  • 1,638
  • 17
  • 17