map in javascript

In JavaScript, the map() method is used to create a new array with the results of calling a provided function on every element in the original array.

The basic syntax of the map() method is as follows:

index.tsx
let newArray = array.map(function(currentValue, index, arr), thisValue)
72 chars
2 lines

You can see that the map() method takes a callback function as an argument. This function takes three parameters: currentValue, index, and arr. currentValue is the value of the current element in the array, index is the index of the current element, and arr is the array being mapped. The thisValue parameter is optional and is used to set the this value inside the callback function.

Here's an example of using the map() method to create a new array with the squares of the numbers in the original array:

index.tsx
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(function(num) {
  return num * num;
});
console.log(squares); // Output: [1, 4, 9, 16, 25]
148 chars
6 lines

In this example, the callback function multiplies each number in the numbers array by itself and returns the result. The map() method creates a new array with the results of this function, which is stored in the squares variable.

You can also use arrow functions with the map() method to make your code more concise:

index.tsx
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
console.log(squares); // Output: [1, 4, 9, 16, 25]
127 chars
4 lines

This does the same thing as the previous example, but with an arrow function instead of a regular function.

related categories

gistlibby LogSnag