DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

JS: Maps can store any type of key

const myMap = new Map([]);

const numberKey = 1;
const stringKey = "str";
const arrayKey = [1, 2, 3];
const objectKey = { name: "abc" };

myMap.set(numberKey, "Number Key");
myMap.set(stringKey, "String Key");
myMap.set(arrayKey, "Array Key");
myMap.set(objectKey, "Object Key");

myMap.forEach((value, key) => console.log(`${key} : ${value}`));

/*
Output:
1 : Number Key
str : String Key
1,2,3 : Array Key
[object Object] : Object Key
*/

Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Discussion (2)

Collapse
bias profile image
Tobias Nickel

yes, it is very good to store meta data about objects, without modifying the object. I think you will love WeakMap for that.