Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/** 
 * 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
}

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading