Open In App

How are elements ordered in a Map in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a new object called Map was introduced in the ES6 version. A map is a collection of elements where each element is stored in a key, value pair. Map objects can store both objects as well as primitive data types. The elements of a map are iterable. Elements are always iterated in the insertion order.

The elements in a map are ordered which means that the elements can be iterated in the order they are inserted. We add the element in the map using the set() method which makes the insertion ordered, it means the element will follow the same order in which they are inserted.

Syntax:

new Map([it])

Example 1:  In this example, we will create a new map object and iterate over it to check how the elements are ordered.

Javascript




const sample = new Map();
sample.set("name", "Rahul");
sample.set("age", 20);
sample.set("Country", "India");
for(let [key, value] of sample){
    console.log(`Key = ${key}, Value=${value}`)
}


Output

Key = name, Value=Rahul
Key = age, Value=20
Key = Country, Value=India

Example 2:  In this example, we will save the keys and values of the map in two different arrays 

Javascript




const sample = new Map();
sample.set("name", "Rahul");
sample.set("age", 20);
sample.set("Country", "India");
 
const keys = sample.keys();
const val = sample.values()
 
let arr= [];
let arr2 = [];
for (let ele of keys){
    arr.push(ele)
}
console.log(arr);
 
for (let ele of val){
    arr2.push(ele)
}
console.log(arr2);


Output

[ 'name', 'age', 'Country' ]
[ 'Rahul', 20, 'India' ]

We can see that the elements maintain the order they are entered in the map so the insertion in new arrays follows the same order as that of the map  



Last Updated : 01 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads