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.tsx72 chars2 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.tsx148 chars6 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.tsx127 chars4 lines
This does the same thing as the previous example, but with an arrow function instead of a regular function.
gistlibby LogSnag