When should I use .map()? When should I use a for loop?
Answer
Use .map() when you want to create a new array of transformed values of the original array by iterating over and calling a function on every element of said original array. Use a for loop when you need a less specialized and more flexible iterator.
// using for loop
function shoutGreetings2(strArray){
let newArray = [ ]
for (let i=0; i< strArray.length; i++){
newArray.push(strArray[i].toUpperCase() + “!”)
}
return newArray
}
The default return value of the .forEach() iterator is undefined while the default return value for .map() is an Array. So if you expect to return an array it’s best to use .map() since you’ll need to write fewer lines of code and thus chances of error are somewhat reduced.
Below is a comparison of for, forEach() and .map()
// using .map()
function shoutGreetings(strArray){
let greet = strArray.map((greeting)=> greeting.toUpperCase() + “!”)
There are many ways you can achieve something. However, you should try to utilize the tools that JavaScript provides which makes coding easier and is more appropriate for the context. I think if we want to loop over arrays, we should use iterators
This was a really great example and it really points out how there are many different ways to solve any problem. In this case, using .map() results in a lot less code.
In fact, I think this can be simplified even further to one line:
const shoutGreetings = arr => {
let newArr =
for (let i = 0; i < arr.length; i++) {
newArr.push(arr[i] + ‘!’);
}
return newArr;
};
I originally done it with .map() but this syntax works too