Let’s learn about array iterators

Scott Brabson
6 min readNov 17, 2020

Easing you into what lies beyond a `For Loop`

For was nice while it lasted, but it’s about time that i = 0 and we move on and learn something new. Let me introduce you to its buddy and your first foray into big kid iteration, .forEach().

I could show you what MDN says, but I imagine you’re here because you’d rather not. That being the case, I’m also going to steer away from using ESMAScript6 and my favorite thicc boi arrows () => in lieu of the more familiar function().

Side by Side: for & forEach

Let’s have a look back at a forloop. Below is one of those iterating through an array of very suspect string values:

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

Not too hard. A bit of extra writing every time you’d like to iterate. It gets the job done. But busting out a for loopin a competitive tech scene is like rolling up to the Indy 500 in your Tonka truck. It’s cute, it got you there, but you’re a kid and the crowd is getting ripped on Montucky Cold Snacks, so you gotta go.

OK. So back to the drawing board. We’ve got a new method:

var noises = ['toots', 'ssssts', 'womps', 'shblirts']noises.forEach(function(noises) {  console.log(noises)})// output: 
// toots
// ssssts
// womps
// shblirts

So a couple things are happening. Let’s start with how the .forEach() method was called. It’s important to know that an array is an object, and in fact it is an object that has its own methods. If you don’t know, a method is essentially a function that belongs to an object…more or less. If you don’t know what an object is inside of JS, well…maybe revisit this article once you do.

When you use .pop(), .push(), you are essentially calling a method of the array object — just like when we call .forEach(). So, the syntax for calling the .forEach() method is the same as calling any of those other, more familiar methods.

Ain’t no call-uh-back gurrrrl

You’ll hear the word ‘callback function’ thrown around a lot. For all intensive purposes, a callback function is a function passed into another function as an argument — that callback function is executed inside of the outer function as part of the outer function’s script…WAT?

Yea, sorry about that.

So, above, the callback function is the nameless (anonymous) function just inside of the .forEach( ), below denoted with a $$callback function$$:

var noises = ['toots', 'ssssts', 'womps', 'shblirts']noises.forEach($$ function(noises) {  console.log(noises)}$$ )

Bear with me. To illustrate what’s happening, the same thing can be accomplished, albeit more stupidly in this example, with a named function. Here we define noiseIterator(), the function to be used as the callback inside of the .forEach(). It does the same exact thing as the anonymous callback function above, only we’ve named and defined it outside of the .forEach():

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

Same as before. The .forEach() is the array iterator method. We pass in the argument noiseIterator as the callback function. The callback function executes on each element, each noise, inside of the array and logs it to the console.

Whew. OK. Callbacks. Got it.

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

So now that we better understand what’s happening with that callback function, let’s look at the variable we’re passing into that callback function as an argument.

Inside of that anonymous callback function, we are passing in the argument noise, which is going to be a single element inside of our noises array. Inside of that anonymous callback function, for each noise within the noises array, we want to console.log() each noise.

But wait — does the AI hive mind somehow know that we are iterating over an array of noises? It somehow knows that the singular of noises is noise? What’s going on here?

No. noise is a label, it is an ephemeral variable title that represents a singular element inside of the array of elements upon which you are calling the .forEach() method. You could use any word you’d like in its place — though best practice is using something that makes sense. For example:

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

This could also be written as:

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

Make sense?

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

OK. OK, I get it. Quicker. More readable. But, what about i? I like i , I need it. What if I need the index of the given array element?

You think i’d lead you astray??

We have access to i, and much more easily. Inside of the callback function, add a comma and then whatever you’d like to denote the index of the given array element — below we use i, because that makes sense, and interpolate it with whatever the value of the current noise is:

var noises = ['toot', 'ssss', 'womp', 'shblirt']noises.forEach(function(noise, i) {    console.log(`${i} ${noise}`)})// output: 
// 0 toots
// 1 ssssts
// 2 womps
// 3 shblirts

COOL!

BONUS: Here’s one more trick. Let’s say you’re iterating over an array using .forEach(), but in order to get that array you needed to first .split(), then .slice(). Instead of declaring a new variable, you can reference that array by adding one more argument to that callback function, below as artArray:

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
})

See, there’s magic in there. Alright, almost done. Last point.

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

OK, so remember this, .forEach() always. returns. undefined. If you’re setting a variable equal to the value returned from a .forEach(), then that variable will have a value similar to your pocketbook after completing your four year bachelor’s of arts — that is nothing (speaking from experience).

Let’s have a look back at that for loop, which yes has its place…:

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

Now, if I were trying to return a value from this for loop with the following:

var noises = ['toots', 'ssssts', 'womps', 'shblirts']for (i = 0; i < noises.length; i++) {  return noises[i]
}
//output: ERROR MO FO!!!

I would get nothing save for the disappointed glares of my peers and of the ghosts of disappointment that fuel my ceaseless drive for self-betterment. Console would yell at you. Unfortunately, console does not make such an explicit point when trying to do the same thing with a .forEach():

var noises = ['toots', 'ssssts', 'womps', 'shblirts']var sounds = noises.forEach(function(noise) {    return noise        
})
console.log(sounds) // output: undefined

sounds is undefined…why? Because like a for loop, .forEach() will always return undefined. So why use a .forEach()? Because like a for loop, you can do all sorts of things with each ‘round’ of iteration inside of the iterator:

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']

Ahhh, so .forEach() is a tool to do something to other things, but not to return a single new value, or any value, ever, because it will always return undefined.

The End.

So there you go. What benefits are offered by .forEach()?

  • Easier to write than a for loop
  • i is implied for each element, though it can be accessed
  • Will get you into the Indy500
  • Is a great introduction to other array iterator methods

Get out there and show ‘em who’s boss. I’ll be back soon with more on array iterator methods. If you liked this or found it helpful, please let me know!

--

--