Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Let's take a look at the forEach() `index` and `array` parameters.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Let me show you just one more thing
about forEach before we move on.
0:00
Let's go the MDN documentation page for
the forEach method.
0:04
You can see here that the callback in
forEach actually accepts some other
0:09
parameters besides the array
element we've been using.
0:13
The second parameter will hold
the index of the current element.
0:17
So if the current value
is the first element, for
0:21
example, the index value will be zero.
0:24
If it's the second element
the index will be one, and so on.
0:27
If your code relies on the position
of the elements in an array,
0:31
this can be helpful to know.
0:35
The third parameter will
hold the whole array itself.
0:37
Neither of these parameters are useful for
most applications, but I just wanted to
0:41
make sure you knew about them in case
you see examples where they're used.
0:46
I'll just demonstrate
the index property quickly.
0:50
Let's say we want to print all
the names in this array here, and
0:54
we want to number them as well.
0:59
I'll just add a second parameter,
the index, to this callback.
1:03
I'll replace this function body
with a call to console.log,
1:14
passing in a template literal.
1:18
Since arrays are zero-based
I'm adding 1 to the index, and
1:21
putting a parenthesis, and then the name.
1:26
I'll delete this console.log
below the loop as well.
1:29
Now when I run this code, You
1:34
can see the index number has been
accessed to provide these numbers.
1:40
One more thing, the index and
1:45
array parameters are available on all of
the array methods we cover in this course.
1:47
If you ever have questions about
what parameters methods accept,
1:52
I recommend checking out MDN for details.
1:56
I've created some additional practice for
you after this video.
1:59
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up