About Lesson
JavaScript Array map()
Method
-
Purpose: Creates a new array by applying a given function to each element of the original array.
-
Syntax:
JavaScriptconst newArray = array.map(callback(element, index, array))
callback
: A function that takes three arguments:element
: The current element being processed in the array.index
: The index of the current element in the array.array
: The original array.
- The
callback
function should return the new value for the current element.
-
Example:
JavaScriptconst numbers = [1, 2, 3]; const squaredNumbers = numbers.map(number => number * number); console.log(squaredNumbers); // Output: [1, 4, 9]
-
Key Points:
- The
map()
method does not modify the original array. It creates a new array with the transformed elements. - The
map()
method is often used to transform data, such as converting units, formatting strings, or applying mathematical operations. - You can use arrow functions concisely within the
map()
method.
- The
Common Use Cases:
-
Data Transformation:
- Converting temperatures from Celsius to Fahrenheit.
- Formatting strings (e.g., capitalizing the first letter of each word).
- Extracting specific data from an array of objects.
-
Creating new arrays:
- Generating a new array with the results of a calculation.
- Creating an array of HTML elements from an array of data.
The map()
method is a powerful tool for transforming and manipulating arrays in JavaScript, providing a concise and efficient way to apply a function to each element.