Learn
Iterators
The .map() Method
The .map()
method is a powerful tool in JavaScript that allows you to iterate over each element of an array and transform it based on a provided callback function. It creates a new array with the results of applying the callback function to each element.
Syntax and Parameters
The syntax for the .map()
method is as follows:
The .map()
method takes a callback function as its argument, which gets executed on each element of the array. The callback function can have three optional parameters:
currentValue
: Represents the current element being processed in the array.index
: Represents the index of the current element being processed.array
: The array on which the.map()
method was called upon.
Additionally, you can pass an optional thisArg
parameter, which represents the value to be used as this
when executing the callback function.
Transforming Data with the .map() Method
One of the key advantages of the .map()
method is its ability to transform data within an array. By implementing a callback function that defines the desired transformation logic, you can easily modify each element of an array without directly modifying the original array.
Here's an example that demonstrates how to use the .map()
method to double each element of an array:
Use Cases of the .map() Method
The .map()
method can be used in various scenarios, such as:
- Transforming an array of objects by extracting a specific property.
- Converting data types within an array.
- Generating a new array with modified elements.
Instructions
Create a new variable called doubledNumbers
and assign it the result of using the .map()
method on the numbers
array:
- Inside the
.map()
method, pass a callback function that takes in a parameternum
. - Inside the callback function, return
num
multiplied by 2.
Print the doubledNumbers
to the console.
Sign up to start coding
Already have an account?
Sign In