devStudent.arrayIterators

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 for loop. Below is one of those iterating through an array of very maturely labeled string values:

var farts = ['toot', 'ssss', 'womp', 'shblirt']for (i = 0; i < farts.length; i++) {    console.log(farts[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/Barbie car, or whichever is least offensive/most relevant. It’s cute, it got you there, but you’re a kid and I’m getting ripped on Montucky Cold Snacks, so you gotta go.

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

var farts = ['toots', 'ssssts', 'womps', 'shblirts']farts.forEach(function(fart) {    console.log(fart)})// 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 farts = ['toots', 'ssssts', 'womps', 'shblirts']farts.forEach($$ function(fart) {    console.log(fart)}$$ )

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 fartIterator(), 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 farts = ['toots', 'ssssts', 'womps', 'shblirts']function fartIterator(argument) {    console.log(argument)
}
farts.forEach(fartIterator) // 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 fartIterator as the callback function. The callback function executes on each element, each fart, 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 fart, which is going to be a single element inside of our farts array. Inside of that anonymous callback function, for each fart within the farts array, we want to console.log() each fart.

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

No. fart 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 fart is:

var farts = ['toot', 'ssss', 'womp', 'shblirt']farts.forEach(function(fart, i) {    console.log(`${i} fart`)})// 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 you will never use again:

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

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

var farts = ['toots', 'ssssts', 'womps', 'shblirts']for (i = 0; i < farts.length; i++) {    return farts[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 farts = ['toots', 'ssssts', 'womps', 'shblirts']var gross = farts.forEach(function(fart) {    return fart        
})
console.log(gross) // output: undefined

gross 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 farts = ['toots', 'ssssts', 'womps', 'shblirts']var bestFarts = [] // we simply declare that gross is an empty arrayfarts.forEach(function(fart) {    if (fart.length > 5) {    // if current element.length > 4 chars        bestFarts.push(fart)  // then do this
}
})
console.log(bestFarts) // 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!

Written by

Front End Dev student at Turing School

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store