Jonnie Grieve Digital Media: Website Blog.

Check out my very latest blogs. For more on particular topics check out the post categories.

100 Days of Code: Day 3 Write-up

For day 3 of “100 days of code” challenge, I turned my attention to practicing forEach loops in JavaScript. All I’m doing today is running through some practice scenarios that use forEach methods.  I’ll do a couple today, for this post.

The first scenario, taken from Treehouse is this…. “Using forEach, add together all the elements in the numbers array, and store the total in the variable total.”

Very straightforward. At first, I tried something like this…

Off the top of my own head…. and it was wrong. I think I was thinking about forEach in PHP, or another iteration method in JS. Anyway, it was wrong.

What I’d wish I’d thought to do was check out the documentation. I’d have seen then, that the forEach method, when assigned to an array works by taking a callback function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Using the new ECMAScript syntax the forEach method looks more like this:

So you have a given array which you call forEach.

– if you want to iterate over an array, that, in its simplest form is how you would do it.

What you then need is an anonymous callback function with a variable as an “iterator” variable.

Taking all this into account, my solution to the challenge was as follows.

Another solution is

numbers.forEach(number => total += number);

It’s essentially the same solution. I merely opted to use curly braces to make clear where the functional part of the anonymous function takes place.

The second challenge, as expected was a little more complicated.  The task said, “Using forEach, copy only the first 2 characters of each string in the days array and store the abbreviations in the dayAbbreviations array“.  But armed with the refreshed knowledge of how to use the method, I got started with

Once I got that far though, I got stuck.

Since there’s an empty array alongside that code, it seemed to me we want to populate array initially with the values of the days array. Then, of course, we need a string manipulation method to retrieve only the first 2 characters of each array value. So I opted for push and substring, hoping to cut array values from the beginning of each string to show only 2 characters.

Substring was okay but it turns out slice() was a better method to use. I’m quite pleased that I thought of push and string manipulation. However my implementation needed a lot of work. The final solution was as follows.

Again, I added console.log() to the function to prove the values were being correctly output.

Leave a Reply

Your email address will not be published. Required fields are marked *