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

107
Vistas
for..in in javascript yields different output than forEach and for loop?

I am surprised i have not faced this until today, but this costed me a whole day as I blindly believed my for...in will work as it should. Please help me understand why this happens with for...in ? Now i'm paranoid to use for...in.

I have simplified the example so that we can just focus on the root cause.

/** map data we are interested in looping */
let map = {
    '0': [],
    '1': ['1']
}

below are the different scenarios and there respective output.

/** 
 * Method 1: Trouble maker
 *
 * details: 
 * when debugged it picks up 1 and then jumps to 0 before going inside
 * the loop for printing console */
for(let val in map['1']){
    console.log(val); // gives 0
}

/** Method 2: using forEach but i cant use return */
map['1'].forEach((pre) => {
    console.log(pre); // gives 1
})

/** Method 3: this is more verbose but can always fallback */
let result = map['1'];
for(let i=0; i< result.length; i++){
    console.log(result[i]); // gives 1
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your for...in loop is wrong. val should be the index of the array, so index 0 would be 1.
Example:

let map = {
    '0': [],
    '1': ['1']
}

const array = map['1'];

for(let index in array){
    console.log(array[index]); // gives 1
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use for ... of

for(let val of map['1']){
    console.log(val);
}

for ... in loops over enumerable properties of an object.

for ... of statement creates a loop iterating over iterable objects.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As you can see from For..in, the for...in statement are used to iterate through the property of an object, i.e. keys/indexes, so the reason that your for...in loop prints 0 is because it printed out each index through your array, which in this case will be "0" since your array only contains 1 element.

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