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

125
Vistas
Proper way of creating an array or pushing into it if it already exists

In my code I have an element, and I want to have it in an array: either the array already exists and then I push my element, or it doesn't and in that case I create the array with this only element:

if (arr) {
  arr.push(elt);
} else {
  arr = [elt];
}

I'm sure there is a better way to do this. I looked into spreading and nullish coalescing operator, but I didn't find any correct syntax. Does anybody have an idea on how I could write my lines with a nicer syntax? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use the expression arr || [] to return an array which is either arr if arr is defined already or [] otherwise. Then you can simply concat the new value to it:

arr = (arr || []).concat([elt])

Note the new value needs to be enclosed in [] to prevent elt values which are arrays from being flattened.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can check if an array exists by testing if it is false-y. Thus, you can create an array if it doesn't already exist with

arr = (arr || []);

From there you can just push your new element:

arr = (arr || []);
arr.push(elt);
about 4 years ago · Juan Pablo Isaza Denunciar

0

See the below code:

if (arr && arr.length > 0) {
  arr.push(elt);
  //or can use spread operator
  arr = [...arr, elt];//this should work if I am not wrong
} else {
  arr = [elt];
}

It is somewhat similar but I guess it should work fine and is a general pattern.

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