Lesson 33 - JavaScript Array Methods – map()
The map()
method is a powerful tool in JavaScript that allows you to transform an array by applying a function to each of its elements, returning a new array.
Explanation
map()
creates a new array populated with the results of calling a provided function on every element in the calling array.- Unlike
forEach()
,map()
returns a new transformed array.
Syntax:
let newArray = array.map(function(currentValue, index, array) {
// return transformed value
});
currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The arraymap
was called upon.
Example 1: Doubling Array Elements
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
- Returns a new array with each number doubled.
Example 2: Using Arrow Functions
let prices = [10, 20, 30];
let discounted = prices.map(price => price * 0.9);
console.log(discounted); // Output: [9, 18, 27]
- Applies a 10% discount using arrow functions.
Example 3: Mapping Objects
let users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
let userNames = users.map(user => user.name);
console.log(userNames); // Output: ['Alice', 'Bob', 'Charlie']
- Extracts specific properties from objects.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson33-map.html
.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 33 - map() Method</title> </head> <body> <h2>Square Numbers</h2> <ul id="squaresList"></ul> <script> let numbers = [2, 3, 4, 5]; let squares = numbers.map(num => num * num); let list = document.getElementById("squaresList"); squares.forEach(square => { let li = document.createElement("li"); li.textContent = square; list.appendChild(li); }); </script> </body> </html>
-
-
Save the File.
-
Open it in a Browser to See the Squared Numbers.
Experiment
- Create an array of product prices and use
map()
to apply a 15% discount. - Convert an array of names into uppercase.
- Map an array of objects to extract only specific properties (e.g., names or emails).
Key Takeaways
map()
returns a new array without modifying the original.- Ideal for transforming data structures.
- Works well with arrow functions for concise code.