The JavaScript array.map() method creates a new array of elements that are the result of calling a provided callback function on every element in the calling array.
This method is useful when you need to apply some logic to the elements of an array, but you also want to keep your original array intact. So, when we apply this method we generate a new array with the modified elements whilst keeping the original array.
- The original array does not change, as it is a copying method
- AnThe callback function is only invoked on array indexes that are not empty
After reading this article, you will have gained an understanding of the JavaScript Array Map() method, along with its use cases, syntax, and examples. You will also learn about the JavaScript Map (introduced in ES6), along with its use cases, syntax, and examples. We will also look at WeakMaps and Objects, and we will compare these with the JavaScript Map.
Syntax of array.map()
// array
const arr = [1, 4, 9]
// Arrow function
arr.map((element) => { /* execute this */ })
arr.map((element, index) => { /* execute this */ })
arr.map((element, index, arr) => { /* execute this */ })
arr.map((element, index, arr) => { /* execute this */ }, thisVal)
// Inline callback function
arr.map(function(element) { /* execute this */ })
arr.map(function(element, index) { /* execute this */ })
arr.map(function(element, index, arr) { /* execute this */ })
arr.map(function(element, index, arr) { /* execute this */ }, thisVal)
// Callback Function
arr.map(callBackFunction)
arr.map(callBackFunction, thisVal)
Parameters
- callBackFunction() - A function to be called on each array element. (Required)
- element - The value of the current element. (Required)
- index - The index of the current element. (Optional)
- arr - The array of the current element. (Optional)
- thisVal - A value passed to the function to be used as ‘this’. If the parameter is not provided, undefined will be used as the ‘this’ value.
Javascript array.map() Examples
Using an arrow function:
const array1 = [1, 2, 8, 10, 15];
// Arrow function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 4, 16, 20, 30]
Using a callback function:
const callBackFunction = (arr) => {
return arr + 1;
};
const array1 = [1, 2, 8, 10, 15];
// pass a function to map
const map1 = array1.map(callBackFunction);
console.log(map1);
// expected output: Array [2, 3, 9, 11, 16]
Expected results: map1 = [ 2, 3, 9, 11, 16 ]
Using map() on Objects
Array of objects representing a Shopping List :
let shoppingList = [
{ item_name: "Apple", quantity: 5 },
{ item_name: "Banana", quantity: 2 },
{ item_name: "Milk", quantity: 4 },
{ item_name: "Pears", quantity: 3 }
];
Iterating over the array of objects:
- Each object in the array of objects is accessed as a function parameter in the callback function of .map()
- The object properties can be de-structured or accessed directly.
// Iterating over array of objects
shoppingList.map(({ item_name, quantity }) => {
console.log(`Item name: ${item_name}, Quantity: ${quantity}`);
}
);
// Expected Output
// Item name: Apple, Quantity: 5
// Item name: Banana, Quantity: 2
// Item name: Milk, Quantity: 4
// Item name: Pears, Quantity: 3
Add a property to each of the shopping list objects:
- In order to add a new property to each object in the shopping list you can use the JavaScript spread operator in the return statement
- The JavaScript spread operator returns the object’s existing properties and values
- Combine the existing properties with a new property to populate the new array with the added property
shoppingList = shoppingList.map(
(item) => {
// New Price Property
const newProperty = "New Property";
return {...item, newProperty: newProperty};
}
);
console.log(shoppingList);
// Expected Output
// Shopping List with new property
// Item name: Apple, Quantity: 5, newProperty: New Property
// Item name: Banana, Quantity: 2, newProperty: New Property
// Item name: Milk, Quantity: 4, newProperty: New Property
// Item name: Pears, Quantity: 3, newProperty: New Property
Deleting a property from each of the shopping list objects:
- Iterate over each object in the array to permanently delete the property
shoppingList = shoppingList.map(
(item) => {
delete item.newProperty;
return item;
}
);
console.log(shoppingList);
// Expected Output
// Item name: Apple, Quantity: 5
// Item name: Banana, Quantity: 2
// Item name: Milk, Quantity: 4
// Item name: Pears, Quantity: 3
JavaScript (ES6) - Map
In 2015, JavaScript (ES6) introduced a new data structure called the Map. Not to be confused with the .map() array method we’ve just discussed,this is a built-in data structure that can be used to store data as a collection of distinct and ordered key-value pairs.
The general syntax to creating a new Map:
let items = new Map();
This creates a variable called items with the value being new Map().
The items variable that we created holds an empty Map.
let items = new Map();
console.log(items)
console.log(items.size)
Output:
Although this new Map is currently empty, there are methods that we can use to manipulate our data after we’ve begun filling our Map.
Map Methods
- map.set() - Adds a key-value pair to the Map
- map.has() - Returns a boolean value after checking whether the specified key is currently in the Map
- map.get() - Returns the corresponding value for a given key
- map.delete() - Deletes the given key-value pair from the Map
- map.clear() - Removes all key-value pairs from the Map
Using the Map Methods
We will use our previous shopping list example to explore the Map data structure.
Using map.set()
let shoppingList = new Map();
shoppingList.set("apple", 2);
shoppingList.set("banana", 5);
shoppingList.set("milk", 4);
shoppingList.set("pears", 3);
// iterating the Map
shoppingList.forEach((val, key) => {
console.log(`Item: ${key}, Quantity: ${val}`);
}
);
// logging the Map size
console.log(`Number of Items: ${shoppingList.size}`);
Output:
After Iterating over the Map, we can see each of the key-value pairs that were set. We can also access the size property to see how this has been updated to reflect the new data.
Using map.has()
console.log(shoppingList.has("milk")); // True
console.log(shoppingList.has('oranges')); // False
Output:
node /tmp/Tk3BQDiIQ6.js
true
false
This shows that true was returned for a key that is within the Map object, and false was returned for a key that is not in the Map.
Using map.get()
console.log(shoppingList.get("apple")); // 2
console.log(shoppingList.get("oranges")); // undefined
Output:
node /tmp/Tk3BQDiIQ6.js
2
undefined
Here we can see that .get() returns undefined when we pass a key that is not within the Map.
Using map.delete()
// deleting the milk from the Map
shoppingList.delete("milk");
// iterating the Map
shoppingList.forEach((val, key) => {
console.log(`Item: ${key}, Quantity: ${val}`);
}
);
// logging the Map size
console.log(`Number of Items: ${shoppingList.size}`);
Output:
node /tmp/Tk3BQDiIQ6.js
Item: apple, Quantity: 2
Item: banana, Quantity: 5
Item: pears, Quantity: 3
Number of Items: 3
The updated Map reflects that the data for the “milk” key has been deleted.
Using map.clear()
shoppingList.clear();
console.log(shoppingList);
console.log(shoppingList.size);
Output:
node /tmp/Tk3BQDiIQ6.js
Map {}
0
And now we can see that the entire Map was cleared, which means the Map is empty and the size is zero.
ES6 JavaScript Map vs Objects
JavaScript Objects are very similar to ES6 Maps as they both let you store collections of key-value pairs, retrieve values, delete keys, and detect if something is stored at the key level.
For a long time, JavaScript Objects have been used to represent Maps. However, there are some important differences between Objects and Maps that you should consider when deciding between the two.
Pros for Map
- Object keys can only be string, integer, and symbol data-types, while Map keys can be any data-type
- The size of a Map can be easily accessed, while the size of an Object has to be tracked manually
- The Map.has(‘key’) method allows you to check whether an element with a specific key exists or not
- The Map has an iterate-in-order feature where the original order of elements is preserved. This ensures the same performance in all browsers
Cons for Map
- Map requires slightly more memory
- JSON support for Objects, but not for Maps (yet)
- Map is purely a hashtable, while an Object offers logic functionality for its elements
ES6 JavaScript Map vs WeakMap
Much like the JavaScript Map, the WeakMap was also introduced in ES6. This allows you to store a collection of Key-Value pairs and it adopts the same properties of the Map object.
The major difference between the two is that the WeakMap key must be an Object data-type. Another difference is that WeakMap’s keys are weakly referenced. This means that whenever an Object is used as a WeakMap key, it can be garbage collected.
For example, if the reference to an Object gets lost (Object reference is assigned to NULL), then the JavaScript garbage collector detects that the Object is no longer in use, and frees it from memory.
The WeakMap Methods:
- .delete() - Removes any value associated with the key
- .set() - Sets the value for the given key in the WeakMap
- .get() - Returns the value associated with the key, or ‘undefined’ if the key is not present
- .has() - Returns a boolean value after checking whether the specified key is currently in the WeakMap
WeakMap Example
// Creating a WeakMap
const shoppingList = new WeakMap();
The code above created a new WeakMap.
Using weakmap.set()
appleObj = { "quantity": 5, "price": 1.5 };
milkObj = { "quantity": 2, "price": 3 };
shoppingList.set(appleObj, "Apple");
shoppingList.set(milkObj, "Milk");
Here we have created two Objects, one for an apple and one for milk. These were then added to the WeakMap as keys.
Logging the WeakMap:
// Print the WeakMap
console.log(shoppingList);
Output:
After console logging the WeakMap’s data, we can see each of the key-pair entries that were added to the WeakMap.
Using .get()
// Using get() function to get
// specific element in WeakMap
console.log(shoppingList.get(appleObj));
Output:
Apple
Calling .get() on the appleObj key returns the stored value, “Apple”.
Using .delete()
// Use delete() function
shoppingList.delete(milkObj);
// Pring the WeakMap
console.log(shoppingList)
Output:
After calling .delete() on the milkObj key, we have removed the key and associated value from the WeakMap. We can then see that the only entry in the WeakMap is the appleObj key and the associated value, “Apple”.
Using.has()
// Using has() function to check
// if a particular element is
// present in WeakMap or not.
console.log(shoppingList.has(milkObj)); // False
console.log(shoppingList.has(appleObj)); // True
Output:
node /tmp/Tk3BQDiIQ6.js
false
true
We can see that the console log output shows false for the milkObj key because it has been deleted, but it outputs true for the appleObj key as this still exists within our WeakMap.
Summary - JavaScript Map Array | JavaScript ES6 Map
In conclusion, we have learned that the JavaScript Map Array is an iterative method to return a new array after performing a callback function on the calling array’s elements. We then covered syntax and use cases for this method. We also learned about the ES6 JavaScript Map and WeakMap, which are built-in JavaScript data structures for key-value pairs. We then covered syntax, use cases, and methods for these structures.
Consider checking out these best JavaScript tutorials to help you further enhance your JS skills.
Have any queries related to JavaScript Map? Let us know in the comments! We’ll do our best to help you out.
The Complete Modern Javascript Course with ES6
Frequently Asked Questions
1. What is a JavaScript Map?
JavaScript Maps are iterables with a key-value pair constructor that looks like a 2D array, but acts like an Object. They offer better flexibility than Objects for keys as they can be any data-type. (Not to be confused with the JavaScript array map method)
2. How do you map an element in JavaScript?
We can map each element in a JavaScript array using the array map method: array.map((currentValue)=>{/* execute this */})
3. Is Map part of ES6?
As part of the ES6 release, the JavaScript community was introduced to a new data collection called the Map. Similar to a JavaScript Object, a Map holds key-value pairs of any type, and it also maintains key insertion order for iteration.
4. Are Maps faster than Objects?
JavaScript Maps tends to perform better than Objects when storing large sets of data, especially when keys are unknown until run time, but also when keys are all of the same data type and values are all of the same data type.
5. Is a JavaScript Map a hashmap?
A JavaScript map can be represented as the Hashtable abstract data type.
People are also reading:
- Best Javascript Courses
- JavaScript Certification
- Best Javascript Books
- JavaScript Interview Questions
- Best Javascript Frameworks
- Best JavaScript IDE
- Javascript Library
- JavaScript UI Library
- TypeScript vs JavaScript
- Difference between Java vs JavaScript
- What is JavaScript Map Array Function?
- Difference between PHP and JavaScript