Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda