map over an array in javascript

To map over an array in JavaScript, you can use the map() method on an array. map() is a higher-order function that takes a function as an argument and applies that function to each element in the array, returning a new array with the results.

Here's an example:

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

const doubledNumbers = numbers.map((num) => {
  return num * 2;
});

console.log(doubledNumbers); // [2, 4, 6, 8, 10]
152 chars
8 lines

In this example, we have an array of numbers and we use map() to create a new array called doubledNumbers. The function we pass to map() takes each number in the original array and multiplies it by 2, returning a new array with the resulting doubled numbers.

map() is useful when you want to transform each element in an array in some way, without modifying the original array. It's a powerful tool in functional programming and makes working with arrays in JavaScript much easier.

gistlibby LogSnag