Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Why doesn't this one-liner that creates an array and pushes to it work?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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), thus the rules of automatic semicolon insertion apply. 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').

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!