javascript / beginner
Snippet
Transforming Arrays with .map()
The .map() method creates a new array by calling a provided function on every element in the calling array. This is the standard way to transform data collections in JavaScript without modifying the original source.
snippet.js
1
2
3
4
5
const numbers = [1, 2, 3, 4];const doubled = numbers.map(function(num) {return num * 2;});console.log(doubled); // [2, 4, 6, 8]
nodejs
Breakdown
1
const numbers = [1, 2, 3, 4];
Defines an initial array of integers.
2
numbers.map(function(num) { ... })
Iterates through each element, passing it into the callback function.
3
return num * 2;
Returns the transformed value for the current element to be placed in the new array.