Why is using javascript “for loop” for array iteration a bad idea?

Sometimes using loop for array iteration can be bad. Let's see how?

Let's create a 10 empty slot array using Array constructor.

const array = Array(10);
console.log(array); //[empty × 10]

Now let's iterate over the array element using for loop. This loop will log Hi 10 times to the console, which we do not want to do.

But our for loop iterates over the empty slot, that is bad for our software performance.

const array = Array(10);
const len = array.length;
console.log(array); //[empty × 10]

for(let i = 0; i < len; i++){
   console.log("Hi");
}

Let's see another example.

const array = [1, 2, 3];
array[4] = 10;

const len = array.length;
for(let i = 0; i < len; i ++){
    console.log("Hi");
}

In the above snippet index 3 of the array is an empty slot, but the console.log will execute 5 times.

Now let's try using one of the array methods.

forEach() method invoked the passed callback function for each element.

But in this case our array slot is empty and our forEach() method is not going to invoke the log function for the empty slot.

So, the below code will print nothing to the console.

const array = Array(10);
const log = () => console.log("Hi");

array.forEach(log); // NOT GOING TO INVOKE THE LOG FUNCTION

If we try our second for...loop example using forEach() method it will execute 4 times. The passed callback function not going to invoke for empty slot.

const array = [1, 2, 3];
array[4] = 10;

const len = array.length;

array.forEach(() => {
    console.log("Hi");
})

Also you can try .map() method insted of for..loop.

26