JavaScript ES6 for-of vs for-in

Posted on Thu, 5/7/2015
1 minute read

Looping in javascript is the best thing ever and I do it all day everyday. I just stumpled upon some of the new ES6 iterators and one stuck out to me a lot. It's called the for-of loop and it much like to a for-in but with one major improvement.

The syntax for both are the same, as shown below:

//ES5
var myArray = ['cheddar','provolone','swiss','parmesan'];
for (var value of myArray) {
  console.log(value);
}

//ES6
let myArray = ['cheddar','provolone','swiss','parmesan'];
for (var value in myArray) {
  console.log(value);
}

Okay, easy enough so what is the difference right? The difference is in the output.

var myArray = ['cheddar','provolone','swiss','parmesan'];
for (var value of myArray) {
  console.log(value);
  // outputs 1,2,3,4
}

let myArray = ['cheddar','provolone','swiss','parmesan'];
for (var value in myArray) {
  console.log(value);
  // outputs 'cheddar','provolone','swiss','parmesan'
}

Do you get the difference? I've always been writing console.log(myArray[value]) to output what for-in outputs out of the box. It's not so life changing change, but it sure is welcomed by me and I appreciate the couple keystrokes this will save me.

Edit May 19, 2015: I did find one thing that might be bad/weird about the for-in loop. It's just a reference to the value and cannot be used to modify the original array.