Looping JS arrays using for-in

Using for-in in Node.js or JS without understanding its proper usage can lead to severe problems. It is misunderstood by many developers who assume it operates like a for loop in other languages like C, Java, Python...etc. However, in JS and Node.js it operates completely differently.

var y = [];
y[2] = 3;
for (var y in a) {
    console.log(x);
}

You will get output as 2 for the above code and sometimes you may get different output also.

var y = []; // here we are creating new array
y[5] = 5;   //Resizing it

for (var x = 0; x < y.length; x++) {
    // iterating over i to 5.
    console.log(y[x]);
}

You may think it will iterate from 1 to 5 but it doesn't iterate.

js Glang output

for..in isn't guaranteed to preserve element ordering

Alternate ways to run for loop in JavaScript

for (var ix = 0; ix < arr.length; ix++) alert(ix);

We can use this method for iterating through an array

Method 1

for (var x = 0; x < a.length; x++) {
    document.write(x + ', ' + typeof i + ', ' + x+1);
}

Ouput

0, number, 1
1, number, 2

Method 2:

for (var i in a) {
    document.write(i + ', ' + typeof i + ', ' + i+1);
}

Ouput

0, string, 01
1, string, 11
...

Real Usage of for-in in js and node js

  • Loops through inherited properties

  • Adding inheritance chain get counter (it is writable, enumerable and configurable property descriptors to false )

  • The for in loop is slow (it is far the fastest method of iteration while looping over Sparse Array)

The sole purpose of the for-in statement is to enumerate the object's properties. This will go up in the prototype chain, enumerating over the inherited properties, which is not desired. Here the iteration order is not guaranteed which means we cannot be sure that the array indexes are visited in the numeric order.

In simple it iterates the overall member of an object(i.e for all enumerable members). An object has arbitrary properties with it.


Further Reading

  1. RuntimeError: Working outside of application context in flask
  2. [SOLVED] ValueError: View function did not return a response
  3. How do you fix UnboundLocalError in Python?

Monitor your software stack for free with Atatus.

Start your free trial
OR
Request a Demo

Free 14-day trial. No credit card required. Cancel anytime.

Ready to see actionable data?

Avail Atatus features for 14 days free-trial. No credit card required. Instant set-up.