All are used for iteration over arrays.

for()

  • basic for loop way of iterating through an array.
  • + Faster for than map and forEach for most environments. (map is faster on some others)
  • – More code

Textbook way:

for (let i = 0; i < array.length; i++ ) {
    // do something with array[i]
}

For ‘in’ way:

For in will loop through the ‘keys’ not through the values.

for (let i in [a, b, c]) {
    // each i will represent an INDEX 0, 1, or 2, not the VALUE “a”, “b”, or “c”
}

Much more useful if you have an object and want the keys.

var obj = {name: johnny, age: 22}
for (let i in obj) {
    console.log(i +  =  + obj[i])
}
// OUTPUT:
// name = johnny
// age = 22

For ‘of’ way:

For of will loop through the values of an array. Only works on collections with the Symbol.iterator property. So For in works with (raw) objects while For of does not. It also works with strings!

for (let i in [a, b, c]) {
    // Each i will represent the actual value, i.e “a”, “b”, or “c”
}

forEach()

Very similar to the ‘For of’ loop.

  • + Less code than regular for loop
  • – No chaining
  • – Slower
var arr = [a, b, c]
arr.forEach(element => console.log(element))
// Returns undefined
// OUTPUT:
// a
// b
// c

Chaining does not work

// WONT WORK. forEach() does not return an array.
arr.forEach(element => element += ab).sort()

map()

Similar to forEach, except it returns an array

  • + Faster than forEach
  • + Less code than forEach (3 characters vs 7)
  • + Allows chaining
var arr = [a, b, c]
arr.map(element => console.log(element))
// Returns an array ([undefined, undefined, undefined] in this case)
// OUTPUT:
// a
// b
// c

We can use the return value of map()

var arr = [a, b, c]
var newArr = arr.map(element => element += ab)
// arr = [“a”, “b”, “c”]
// newArr = [“aab”, “bab”, “cab”]

And we can chain together other methods with map()

var arr = [c, b, a]
arrOne = arr.map(element => element = ab + element)
// arrOne = [“abc”, “abb”, “aba”]
arrTwo = arr.map(element => element = ab + element).sorted()
// arrTwo = [“aba”, “abb”, “abc”]