JavaScript Map Object [ES6]

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
525
Reaction score
739
First Language
English
Primarily Uses
RMMV
You can find the original post here.

The Map Object
In ES6, JavaScript added a new Map class. The Map class is very similar to the standard object class, with a few differences. Today, we’re going over when to use and why to use them.

Why Map
Map, unlike the object class, does not have extra keys that have to be enumerated. This saves time when iterating over values in the map. The second thing is that a map can have a key of any type where an object’s key must be a string. Lastly, a map has built-in functions for getting values.

The key functions of a map are set, get, has, and delete. “set” adds the key-value pair to the map. “get” retrieves the value of the key. “has” checks if the key exists. Lastly, “delete” removes the key-value pair from the map without error. Each function provides a lot of value to the map class, which is better than spending time coercing an object to do the same job; this makes maps very useful.

These three things make the map extremely useful in situations where key-value pairs need to be stored. The built-in functions add flexibility that a basic object can’t provide. Here’s an example of using a map vs using an object.

JavaScript:
// Map Example

const a = new Map();
const b = {};

//Adding key-value pairs
console.log("Set Key");
//Map
a.set('test', 3);
console.log(...a.entries()); //[ 'test', 3 ]
//Object
b['test'] = 3;
console.log(b); //{ test: 3 }
//Get key
console.log("\nGet Key");
//Map
const c = a.get('test');
console.log("Map:", c);//Map: 3
//Object
const d = b['test'];
console.log("Object:", d); //Object: 3


//Has key
console.log("\nHas Test");
//Map
console.log("Map:", a.has('test')); //true

//Object
console.log("Object:", b['test'] !== undefined); //true (But could be set to null or undefined by developer)

//Remove key
console.log("\nDelete Key");
//Map
console.log("Map:", a.delete('test')); //true if there is a key to remove
console.log("Map:", a.get('test')); //Map: undefined
//Object
delete b['test'];
console.log("Object:",b['test']); //Object: undefined
So, that’s why to use a map, so what about when?


When To Use Map
A map should be used in select areas of your code. Given the “why”, they should be used when you need to store key-value pairs while the program is running. This is because maps can have keys that can’t be serialized properly in JSON. Furthermore, they would have to be coerced before being serialized. Although it’s not hard, if you only use strings as keys; using more complex keys will be trouble. So, use a map when you need to store key-value pairs that won’t be serialized. With that said, the map object provides a ton of value.

Conclusion
Maps are a great addition to the JavaScript language and have many uses. Although they shouldn’t be serialized, they come with built-in functions that make getting and looking up key-value pairs simple. The next time you think of using an object for storage, consider a map. Happy coding!

Sources
Map
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,398
Reaction score
3,374
First Language
English
Maps are nice. I alway use them in ruby, and in ES5 they didn't have a map type so it was kind sad. Object sort of worked but at the same time, didn't really have a nice interface to work with.

I generally avoid using mutable objects as keys. Stick with things like numbers and strings. Use actor ID's instead of Actor objects, etc.
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
525
Reaction score
739
First Language
English
Primarily Uses
RMMV
I agree with this 100%. My opinions have changed over the years and I definitely prefer immutable code where possible including in Maps!
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

ESAMarathon on Twitch, now streaming "Eat Girl". Yep, that's the title of a game... Apparently it's a Pacman knockoff.... Which is of course the only logical conclusion one would get from a name like "Eat Girl". :kaopride: I can't believe anybody would think anything else! :kaoback:
Super stoked i just finished my first town in my project, by finished i mean i can always add more decorative aesthetics and the NPCs don't talk yet but the mapping is complete and all the important chess pieces are present!
My brain: Hey, I have an idea how to make the transition to the main story quest in The Wastes more natural!
Me: Good!
My brain: You need to remake the hotel you start out in, it's not realistic enough.
Me: Ok... This was unexpected, but I can do it.
My brain: Now make each hotel floor 5 times as large to match the main part. Oh, you also need to make a bunch of new npcs to fill in the space on these maps.
Me: Crap.
Should be able to release Haxe MV/MZ next weekend.
It look that somehow MZ tracks are messed up (for example battle4 is obviously a theme, castle2 is a ship, ship1 is a scene and so on..). Maybe they just named them after with some ambiguity.

Forum statistics

Threads
100,618
Messages
977,838
Members
132,228
Latest member
zhengdddddd
Top