You're doing this wrong. You can shorten this using the inbuilt map function. For example,
let arr1 = [1, 2, 3]
let arr2 = arr1.map(item => item * 3)
console.log(arr2) // [3, 6, 9]
This is much more concise. This doesn't use any external iterators. This also doesn't mutate the original array(though you also don't mutate it in your example). This is more readable if you know what map is.
So this is how map works: You call map
on an Array
and pass it a function. This is where a function being first class comes into picture. You're passing it to another function. Map basically takes this function and the array and calls this function on each entry in the array. The value your function returns is stored in another array at the corresponding indices and this newly constructed array is returned by map.
Head over to MDN Docs to learn more about map, how it works and some more examples. There are other functions like filter, reduce, etc that once you learn are very hard to not use while writing JS. Read through all the examples for these three functions and try to apply them when you code.
I'll just put this code here so that you can see how concise and expressive it can be to use these functions once you understand their syntax and what they do.
let myArr = [1,2,3,4,5,6,7,8,9]
let sumOfDoubleOfOddNumbers = myArr.filter(num => num % 2)
.map(num => num * 2)
.reduce((acc, currVal) => acc + currVal, 0);
First we filter out all numbers that do not pass the test. Then we double all these filtered numbers. Finally using a reducer and a starting value we reduced this array down to a final value. In this process, we used 3 different functions that were passed as arguments(reiterating on the functions being first class citizens point).