Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda