Notes

JavaScript - Difference between for, foreach, for...in, for...of

author: Paul Kim

categories: js

tags: js

Difference between for, foreach, for...in, for...of

for

repeat until a specified condition evaluates to false

var i
for (i = 0; i < 5; i++) {
  console.log(i)
}

forEach

execute a provided function once for each element in Array, TypedArray, Map, Set, or possibly NodeList.

  • Array.prototype.forEach()

    ;['a', 'b', 'c'].forEach(function (element) {
    console.log(element)
    })
    // expected output: "a"
    // expected output: "b"
    // expected output: "c"
    
    // Notice that index 2 is skipped since there is no item at
    // that position in the array.
    ;[2, 5, , 9].forEach(function (element, index, array) {
    console.log('a[' + index + '] = ' + element)
    })
    // logs:
    // a[0] = 2
    // a[1] = 5
    // a[3] = 9
  • TypedArray.prototype.forEach()

    new Uint8Array([0, 1, 2, 3]).forEach(function (element, index, array) {
    console.log('a[' + index + '] = ' + element)
    })
    // logs:
    // a[0] = 0
    // a[1] = 1
    // a[2] = 2
    // a[3] = 3
  • Map.prototype.forEach()

    new Map([
    ['foo', 3],
    ['bar', {}],
    ['baz', undefined],
    ]).forEach(function (value, key, map) {
    console.log(`m[${key}] = ${value}`)
    })
    // expected output: "m[foo] = 3"
    // expected output: "m[bar] = [object Object]"
    // expected output: "m[baz] = undefined"
    
    new Map([
    ['foo', 3],
    ['bar', {}],
    ['baz', undefined],
    ]).forEach(function (value, key, map) {
    console.log(`map.get('${key}') = ${value}`)
    })
    // logs:
    // "map.get('foo') = 3"
    // "map.get('bar') = [object Object]"
    // "map.get('baz') = undefined"
  • Set.prototype.forEach()

    new Set(['foo', 'bar', undefined]).forEach(function (value1, value2, set) {
    console.log('s[' + value1 + '] = ' + value2)
    })
    // expected output: "s[foo] = foo"
    // expected output: "s[bar] = bar"
    // expected output: "s[undefined] = undefined"
    
    new Set(['foo', 'bar', undefined]).forEach(function (value1, value2, set) {
    console.log('s[' + value1 + '] = ' + value2)
    })
    // logs:
    // "s[foo] = foo"
    // "s[bar] = bar"
    // "s[undefined] = undefined"
  • NodeList.prototype.forEach()

    var node = document.createElement('div')
    node.appendChild(document.createElement('p'))
    node.appendChild(document.createTextNode('hey'))
    node.appendChild(document.createElement('span'))
    node.childNodes.forEach(function (currentValue, currentIndex, listObj) {
    console.log(currentValue + ', ' + currentIndex + ', ' + this)
    }, 'myThisArg')
    // results in:
    // [object HTMLParagraphElement], 0, myThisArg
    // [object Text], 1, myThisArg
    // [object HTMLSpanElement], 2, myThisArg

for...in

iterate over all enumerable properties of an object

for (var i in obj) {
  console.log(i)
  console.log(obj[i])
}

Note: you shouldn't use for...in statement to iterate over Array elements because it will return user-defined properties in addition to the numeric indexes.

for...of

creates a loop iterating over iterable objects (including Array, Map, Set, arguments object and so on)

var arr = [3, 5, 7]
arr.foo = 'hello'

for (var i in arr) {
  console.log(i) // logs "0", "1", "2", "foo"
}

for (var i of arr) {
  console.log(i) // logs 3, 5, 7
}
Source

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.