use map with a list in javascript

The map() method is a higher-order function in JavaScript that allows iterating through arrays and transforming each element into a new array. Below is an example of how to use map() with a list in JavaScript:

index.tsx
const numbers = [1, 2, 3, 4, 5];

// Using map to transform all integers into their square
const squares = numbers.map(num => num * num);

console.log(squares); // Output: [1, 4, 9, 16, 25]
190 chars
7 lines

In this example, we have declared an array of numbers and then used the map() method to create a new array called squares. The map() method takes a function as an argument that is applied to each element of the original array (numbers in this case). In this example, we are using an arrow function to square each number.

After the map() method is applied, squares array contains the squared values of each number from the numbers array.

Note that the map() method does not modify the original array. Instead, it returns a new transformed array.

gistlibby LogSnag