Let’s learn about array iterators

Easing you into what lies beyond a `For Loop`

Side by Side: for & forEach

var noises = ['toot', 'ssss', 'womp', 'shblirt']for (i = 0; i < noises.length; i++) {  console.log(noises[i])}// output: 
// toot
// ssss
// womp
// shblirt
var noises = ['toots', 'ssssts', 'womps', 'shblirts']noises.forEach(function(noises) {  console.log(noises)})// output: 
// toots
// ssssts
// womps
// shblirts

Ain’t no call-uh-back gurrrrl

var noises = ['toots', 'ssssts', 'womps', 'shblirts']noises.forEach($$ function(noises) {  console.log(noises)}$$ )
var noises = ['toots', 'ssssts', 'womps', 'shblirts']function noiseIterator(argument) {    console.log(argument)
}
noises.forEach(noiseIterator) // there are no parenthesis - that would
// cause the function be called
// the moment that the script loads
// output:
// toots
// ssssts
// womps
// shblirts

GREAT. What’s with the variable being called whatever it wants???

var nums = [1, 2, 3, 4, 5]nums.forEach(function(number) {    console.log(number)
})
// Output:
// 1
// 2
// 3
// 4
// 5
var nums = [1, 2, 3, 4, 5]nums.forEach(function(banana) {console.log(banana)
})
// Output:
// 1
// 2
// 3
// 4
// 5

Alright. Making sense. What about i though? I need i.

var noises = ['toot', 'ssss', 'womp', 'shblirt']noises.forEach(function(noise, i) {    console.log(`${i} ${noise}`)})// output: 
// 0 toots
// 1 ssssts
// 2 womps
// 3 shblirts
var farts = 'farts'
farts.split('').slice(1, 4) // this would output ['a','r','t']
farts.split('').slice(1, 4).forEach(function(letter, i, artArray) { console.log(artArray) // will log ['a','r','t'] three times
})

Like our bachelor’s degrees, .forEach() will always return NOTHING (undefined)

var noises = ['toots', 'ssssts', 'womps', 'shblirts']for (i = 0; i < noises.length; i++) {  console.log(noises[i])}// output:
// toots
// ssssts
// womps
// shblirts
var noises = ['toots', 'ssssts', 'womps', 'shblirts']for (i = 0; i < noises.length; i++) {  return noises[i]
}
//output: ERROR MO FO!!!
var noises = ['toots', 'ssssts', 'womps', 'shblirts']var sounds = noises.forEach(function(noise) {    return noise        
})
console.log(sounds) // output: undefined
var noises = ['toots', 'ssssts', 'womps', 'shblirts']var bestNoises = [] // we simply declare that bestNoises is an empty arraynoises.forEach(function(noise) {    if (noise.length > 5) {    // if current element.length > 4 chars        bestNoises.push(noise)  // then do this
}
})
console.log(bestNoises) // output: ['sssts', 'shblirts']

The End.

Front End Dev student at Turing School