Home > Net >  Why doesn't this one-liner that creates an array and pushes to it work?
Why doesn't this one-liner that creates an array and pushes to it work?

Time:07-09

When I run this code, it works, as you would expect:

var b = {}
b['foo']=[]
b['foo'].push(1)

But when I try doing this as a one-liner, like this:

var b = {}
(b['foo']=[]).push(1)

It throws: Cannot set properties of undefined (setting 'foo'), even though b is very clearly defined.

Could someone explain this behavior? Thanks in advance.

Edit: For some reason, adding the semicolon fixes the issue, which confirms that the compiler was in fact trying to run it as a function. But now I have another question: Why did it throw an error saying b is not defined, instead of b is not a function?

CodePudding user response:

As noted by Reyno, this is parsed as

var b = {}(b['foo']=[]).push(1)

since there is no semicolon delimiting var b = {} and (b['foo']=[]).push(1). The question that remains is why this throws

Cannot set properties of undefined (setting 'foo')

rather than

Uncaught TypeError: {} is not a function

which ought to be thrown for {}(). The reason for this is that

var b = {}(b['foo']=[]).push(1)

is equivalent to

var b; b = {}(b['foo']=[]).push(1)

The right-hand side of the assignment is evaluated first, so before the call is made, it evaluates b['foo'] to evaluate the inner assignment, but b is undefined, leading to the error Cannot set properties of undefined (setting 'foo').

  • Related