What is the difference between ( for ... in ) and ( for ... of ) in javascript?
October 26, 2018
A for...in
loop will loop over property names (not values) in an object. However the for ... of
loop will loop over iterable objects. Read on for a description of what this means:
Here is what for ... in
looks like, and what it outputs:
var array = [22, 33, 44];
array.foo = "hello";
for (var i in array) {
console.log(i); // logs "0", "1", "2", "foo"
// notice that it does not output 22/33/44
}
Notice that it outputs the property names (i.e. 0,1,2 for the 3 initial values in the array, then 'foo' (NOT hello).
Here is how it looks for for ... in
...
var array = [22, 33, 44];
array.foo = "hello";
for (var i of array) {
console.log(i); // logs "22", "33", "44"
//it is does not log "22", "33", "44","hello"
}
It only includes the initial ones (22/33/44), not foo.
A good way to remember this:
"A mnemonic: 'o'f -> not 'o'bjects, 'i'n -> not 'i'terables" (source)
When was for in
added to JS
It was standardized in ES6.