Skip to content
Advertisement

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.

JavaScript

below are the different scenarios and there respective output.

JavaScript

Advertisement

Answer

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement