Changing Every Element with map
In the Functions section you passed a function to another function. Arrays have several methods built on this idea. You give them a callback, and they do the looping for you. The first one is map. It runs your callback on every element and collects the results in a new array:
const nums = [5, 3, 8];
console.log(nums.map(n => n * 2));
console.log(nums.map(n => n + " kg"));
console.log(nums);
Output:
[ 10, 6, 16 ]
[ '5 kg', '3 kg', '8 kg' ]
[ 5, 3, 8 ]
The new array always has the same number of elements as the original, in the same order. Each element is whatever your callback returned for it. The last line shows that map does not change the original array.
Here is the same work done with a loop:
<!-- continues -->const doubled = [];
for (const n of nums) {
doubled.push(n * 2);
}
console.log(doubled);
Output:
[ 10, 6, 16 ]
The loop needs an empty array, a for...of and a push. With map, you only write the part that matters: n => n * 2.
The callback can return a different type from the one it gets. The second line of the first example turned numbers into strings. You can also go the other way. Number is a function, so you can pass it to map to turn strings into numbers:
const parts = "4 8 15".split(" ");
console.log(parts);
console.log(parts.map(Number));
Output:
[ '4', '8', '15' ]
[ 4, 8, 15 ]
Notice that you write Number without parentheses. You pass the function itself, and map calls it once for each piece. From now on, the exercises read a line of numbers in one step: lines[0].split(" ").map(Number).
Should you use map or forEach? Use map when you want a new array. Use forEach when you only want to do something with each element, such as print it. forEach gives nothing back, so its result is undefined:
console.log(parts.forEach(p => p));
console.log(parts.map(p => p));
Output:
undefined
[ '4', '8', '15' ]
In the exercise, use map to square each number and to add a "cm" label to each one.