javascript maps

 

JavaScript Maps (Map Object)

1) What is a Map?

A Map is a built-in JavaScript object used to store key–value pairs where:

  • Keys can be any data type (string, number, object, function).

  • Insertion order is preserved.

  • It is different from a plain object {}.


2) Create a Map

const map = new Map();

With initial values:

const map = new Map([
  ["name", "Sushant"],
  ["age", 23],
  [true, "active"]
]);

3) Common Methods

set(key, value)

map.set("city", "Pune");

get(key)

map.get("name"); // "Sushant"

has(key)

map.has("age"); // true

delete(key)

map.delete("age");

size

map.size; // number of entries

clear()

map.clear();

4) Looping over a Map

for...of

for (let [key, value] of map) {
  console.log(key, value);
}

keys(), values(), entries()

map.keys();
map.values();
map.entries();

5) Map vs Object (Important)

FeatureMapObject
Key typesAnyString / Symbol
OrderPreservedNot guaranteed
Sizemap.sizeManual
IterationEasyNeeds extra methods

6) Real-life Example

const userVisits = new Map();

userVisits.set("Sushant", 5);
userVisits.set("Rahul", 2);

console.log(userVisits.get("Sushant")); // 5

7) When to Use Map

  • Dynamic keys

  • Frequent add/remove operations

  • Need guaranteed order

  • Better performance than objects in such cases


8) Common Mistake

map["name"] = "ABC"; // ❌ wrong
map.set("name", "ABC"); // ✅ correct

If you want:

  • practice questions

  • Map vs Array.map() difference

  • interview questions

  • real projects using Map

state the next topic.

Comments

Popular posts from this blog

else-if condition in if-else statements: Concatenation in JavaScript :

LCM & HCF- Tricks

Day 9: CSS - Font Formate