Table of contents
- What is JavaScript map?
- JavaScript map syntax
- JavaScript map methods and use cases
- Return a value mapped to a specific key
- Return a boolean value showing whether a specified key exists
- ber of entries in the map
- Return a new iterator object that includes the value of each element
- Remove specified elements from map object
- Remove all elements in map object
- More important map methods:
JavaScript was confined with its collections talents. In different languages, you could work with sets, associative maps, lists, and dictionaries, however JavaScript simplest allowed you to paintings with arrays. JavaScript builders located a way to map keys to values, however their technique came with its very own boundaries.
In the ES6 launch, JavaScript brought a new built-in elegance for maps that makes it less complicated to paintings with collections. In this brief academic, we’ll talk JavaScript Map code examples, methods, and use instances
What is JavaScript map?
Before ES6, JavaScript builders used gadgets to map keys to values, however using an item as a map has a few restrictions:
- There’s no reliable manner to iterate over keys
- The keys() technique converts fields to strings, which creates key collision
- There’s no simple manner to feature new keys and new values
These problems were addressed within the ES6 release while the Map collection type became introduced. It can preserve key-price pairs of any type and may don't forget key insertion order. Any fee (gadgets and primitives) may be used as a key or a value.
JavaScript Map creates a brand new array, which includes the results from the new release over the elements of the array and calls the furnished function once for each element in order. It’s an vital records shape that has many essential makes use o
Note: WeakMap is similar to Map, but all keys in a WeakMap are objects.
To create a new Map, follow this syntax:
let map = new Map([iterable]);
Let’s say we want to create one that stores names as keys and scores as values
'use strict';
//START:DEFINE
const scores =
new Map([['Ruby', 12], ['Steven', 11], ['Sam', 15], ['Robin', 14]]);
scores.set('James', 14);
console.log(scores.size);
//END:DEFINE
We did three things here:
- Initialized the scores map with names and scores
- Added a key and value to the map using the set() method (line 7)
- Used the size property to determine how many keys are in the map (line 9)
There’s a lot more we can do with JavaScript maps, such as:
- Iterate through maps
- Initialize maps with iterable objects
- Get elements from maps by key
- Get the number of elements in a map
- Convert map keys or values to arrays
- Invoke callbacks for each key-value pair in insertion order
- Etc.
Before we dive deeper into some methods and use cases, let’s first learn the JavaScript map syntax.
JavaScript map syntax
This JavaScript map syntax is as follows:
Description:
- array: the array on which the specific function is called
map: the method called for the array with the required parameters function(currentValue, index, arr): the function with its parameters, which is required to run for each element in the array
currentValue: the value of the current element
index: the index of the current element
arr: the array object on which the map() is called
thisValue: the value used as the function’s this value when it’s executed
Now that we’ve learned the syntax, let’s look at an example implementation of the map() function:
//creating an array
var an_array = [5, 3, 1, 4, 2]
//map calls a function with “item” as parameter
//map will pass each element of an_array as “item” in this function
//the function will triple each element passed and return it as the return value
result = an_array.map(function(item) {
return item*3;
});
//new list will print with the tripled values
console.log(result);
JavaScript map methods and use cases
### Initialize a map with an iterable object
The Map() constructor initializes a map with an iterable object:
```
let userRoles = new Map( [
[ruby, 'director'],
[steven, 'producer'],
[foo, 'writer'],
[robin, 'actress']
]);
```
Return a value mapped to a specific key
get() returns a value mapped to a specific key:
```
userRoles.get(robin); // actress
```
If you pass a key that’s not in the map, it will return as undefined:
let emma = {name: 'Emma'};
userRoles.get(emma); // undefined
Return a boolean value showing whether a specified key exists
has() returns a boolean value showing whether a specified key exists:
userRoles.has(emma); // false
userRoles.has(ruby); // true
ber of entries in the map
The size property returns the number of entries in the map:
console.log(userRoles.size); // 4
Return a new iterator object that includes the value of each element
values() returns a new iterator object that includes the value of each element:
for (let role of userRoles.values()) {
console.log(role);
}
// director
// producer
// writer
// actress
Remove specified elements from map object
delete() removes specified elements from map object:
userRoles.delete(ruby);
Remove all elements in map object
clear() removes all elements in map object:
userRoles.clear();
If we checked the size, it would return as zero:
console.log(userRoles.size); // 0
More important map methods:
forEach(callback[, thisArg]): invokes a callback for each key-pair value in the map in insertion order
set(key, value): sets the value for the key in the map object
keys(): returns a new iterator with the keys for elements in insertion order
entries(): iterates over a collection of keys and values