When it comes to looping through arrays and performing a function on each item, there are three common methods that you should be familiar with:
for
forEach
map
For this week, we are going to practice using these in order to gain familiarity with each one and when one is better to use than another.
Code Challenge
Data
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Scenarios
For each problem below, write out as many versions of the solution as possible for practice:
- Double the value of every item in
list
- Transform each item in
list
to be a string " o'clock" appended to the current item (i.e.,1
becomes"1 o'clock"
) - Replace every item that is divisble by 3 with the string "triforce"
- Only loop through items that have an even index. In other words, the loop should only run 5 times.
Extra Credit
- What is the advantage of using a
for
loop over the other two methods? - What is the difference between
forEach
andmap
?
Guidelines
- You can use any language you want to solve it. Just know that the solution will be devised and written via JavaScript.
- Try and devise the solution on your own for at least 15 minutes before checking the internet for ideas.
- If you do use other resources to help you come up with the solution, no copying and pasting! Make sure to type it all out so that you get the repetition to reinforce what you're doing.
Good luck!