MAPS
A map is a data structure which maps values (keys) with other values.
In Javascript we can use an Object for this purpose.
Suppose we've to store student's marks, we can use an object for this purpose.
let marks={
"John": 98,
"Arun": 87,
"Robert": 91
};
console.log(`Arun scored ${marks["Arun"]} marks.`);
// → Arun scored 87 marks.
console.log("Are Julie's marks known?", "Julie" in marks);
// → Are Julie's marks known? false
console.log("Are toString's marks known?", "toString" in marks);
// → Are toString's marks known? true
Although the first 2 results were expected, we certainly didn't expect the 3rd result as we didn't add any key with the name of 'toString' to our marks object.
But this is the downside of using an Object
as a Map
.
Along with the key-value pairs we define the plain object also derives properties from Object.prototype
Hence using plain objects as maps could be dangerous. So suppose we want an object without it inheriting from Object.prototype
, we can do this in many ways:
One of the way is to pass null
to Object.create()
method. In this way the resulting object will not derive from Object.prototype
and can be safely used as a map.
console.log("toString" in Object.create(null));
// → false
Also if we're using a plain object as our map, we can avoid using in
keyword for finding whether key is present in object or not; instead we can use hasOwnProperty()
method which ignores the object's prototype.
console.log({x: 1}.hasOwnProperty("x"));
// → true
console.log({x: 1}.hasOwnProperty("toString"));
// → false
There's another problem with using plain objects. It only accepts strings as it's keys. And if suppose we want suppose an object as a key, we cannot do this.
Don't worry, Javascript also provides us with Map
class which is written for this exact purpose.
The methods set
, get
, and has
are part of the interface of the Map object.
let marks = new Map();
marks.set("John",98);
marks.set("Arun",87);
marks.set("Robert",91);
console.log(`Arun scored ${marks.get("Arun")} marks.`);
// → Júlia scored 87 marks.
console.log("Are Julie's marks known?", marks.has("Julie"));
// → Are Julie's marks known? false
console.log("Are toString's marks known?", marks.has("toString"));
// → Are toString's marks known? false
References: