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

115
Vistas
Unable to push elements in a new array in javascript

I am writing a very easy function where I am checking the even numbers from an array of integer and adding those even numbers into the new array. But after getting the even numbers from first array when I am trying to push into second array its showing undefined.

const arr = [1,2,3,4,5,6];
const newArr = [];

const loop = () => {
 for (var item of array) {
  if (item % 2 == 0) {
   console.log(item);
   newArr.push(item);
  }
 }
};

console.log(loop());     

Output

2 4 6 undefined

Why new array is showing undefined.

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

0

You can do it simply with forEach.

const arr = [1,2,3,4,5,6];
const newArr = [];


arr.forEach(item => {
  if (item % 2 == 0) {
   newArr.push(item);
  }
})

console.log(newArr);     

about 4 years ago · Juan Pablo Isaza Denunciar

0

either return the newArray or execute the loop method and print the new Array.

The reason why you get undefined is because loop is currently a void operator and returning nothing. so if you want the loop method to return the array then the second code sample I showed is the better solution. if you just want to print the array then the first one does the trick.

const arr = [1,2,3,4,5,6];
const newArr = [];


arr.forEach(item => {
  if (item % 2 == 0) {
   newArr.push(item);
  }
})

console.log(newArr); 

or

const arr = [1,2,3,4,5,6];

const loop = () => {
 const newArr = [];
 for (var item of arr) {
  if (item % 2 == 0) {
   console.log(item);
   newArr.push(item);
  }
 }
 return newArr
};
console.log(loop());  

both will work.

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