JS Quiz: Easy: Basic Map Initialization

What will be the size of the myMap after this code runs?

const myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);
  • 0
  • 1
  • 2
  • undefined
0 voters

It will be 2. Each set() call adds a new entry to the Map, so two distinct calls for ‘a’ and ‘b’ will result in two entries.

const myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);

If you tried to set the same key twice, like myMap.set('a', 1); myMap.set('a', 3); , it would just update the value for ‘a’ and the size would still be 1.

It’s a common point of confusion for people moving from plain objects.

JS Quiz answer: Option 3 (C).

Correct choice: 2

Why:
A Map stores key-value pairs. The set() method adds new pairs to the map. In this code, two distinct key-value pairs (‘a’, 1) and (‘b’, 2) are added to myMap, resulting in a size of 2.

Go deeper:

Using JavaScript Prototype To Add New Properties

First-answer leaderboard

  1. @kirupa - 5 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @Apexcodes - 2 (firsts)
  4. @emmawalter5 - 1 (first)

Okay so the set() method is basically just pushing new entries. each one is unique here so the size grows.

Clean

Yeah, new Map() is just so clean for this. no fuss, just works.

It’s clean until you need to serialize it for an API, then you’re back to Object.fromEntries(myMap). That’s where the “no fuss” part gets a bit more complicated.

You’re right, serializing a Map for an API often means converting it back to a plain object. This article on converting between Maps and Objects might help streamline that process:

https://www.kirupa.com/html5/map_object_conversion.htm

2 — the map contains two entries: a and b. You can check it with myMap.size.

lol good guess @Apexcodes. we’ll see if that’s the magic number when I drop the answer later today.

I like using Map objects too. They are good for keeping track of related data, like connecting a building material to its supplier.

Yeah, I use Map a lot for UI stuff too, especially when I need to quickly look up an element’s data based on the element itself. It’s like having a little address book just for your components.

I’ve seen Map used for tracking component state in some pretty complex UIs. It’s solid for that. My main concern is always memory if you’re not careful about clearing references.

Memory management is something I always think about with architecture too. If you don’t plan for how a building changes, it can become very inefficient.

Wait so you’re talking about like, not just if the building gets bigger but if its purpose changes? like a library becoming a co-working space? that’s a whole different kind of refactor.

That’s a good way to put it. A library becoming a co-working space means the flow of people, the light, even the sound expectations are completely different.