JavaScript Quirk: for() and forEach

Today’s little nugget of awesomeness concerns a small but nifty difference between JavaScript’s inbuilt for loop and the fancier, more performant forEach.

let arr = new Array(100);

arr[0] = 0;
arr[20] = 20;

for (let i=0; i<arr.length; i++) {
  console.log(for); //logged 20 times

arr.forEach(el => console.log("forEach")); //logged twice

What is apparent here is that, as opposed to for,
forEach skips uninitialized (or, in fact, deleted) index properties.

Many a blog post and Stack Overflow answer has been written on the subject of performance differences between native and naive JavaScript functions. And realistically, the above’s influence over performace would likely be minimal in most of your JavaScript looping scenarios. But it’s still a neat little knack to be aware of if you aren’t already, so there!