Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Practice forEach in JavaScript!
You have completed Practice forEach in JavaScript!
Preview
Let's walkthrough the solution to the third code challenge.
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
In this challenge we need
to use the forEach method
0:00
to turn the number strings in
the stringPrices array into floats.
0:03
And then we need to add them all together,
0:08
storing the total in
the variable named total.
0:10
I'll start with copy and
pasting the code for
0:13
this challenge into Atom in order
to make the code easier to read.
0:15
Again, I started by adding
the call to the forEach method.
0:23
And then the anonymous callback
function using arrow function syntax.
0:26
So, stringPrices.forEach.
0:30
And I use stringPrice for the current
value parameter name, followed by a fat
0:35
arrow For the function body, I added a set
of curly braces to define a code block.
0:41
Each price is a string, so we need to
convert it to a number before we can
0:47
successfully add it to
the priceTotal variable.
0:52
To do that, I use the parseFloat function.
0:55
First, let's define a variable.
0:57
So const price equals
parseFloat(stringPrice).
0:59
Then I use the addition
assignment operator to add
1:09
the current price to
the priceTotal variable.
1:13
priceTotal += price;.
1:16
And that's my solution.
1:21
Like we did with the previous example,
1:22
you could eliminate
the intermediate variable price.
1:24
Cut this code, delete that line, and
1:31
replace price here of
the call to parseFloat.
1:35
And we could also
eliminate the curly braces.
1:39
Nice job.
1:44
Coming up,
the next challenge of the course.
1:46
And we'll see you after that.
1:48
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