JavaScript Maps

JavaScript Tutorial

JavaScript Maps

In JavaScript Maps is a collection of key-value pairs in JavaScript. Unlike objects, Maps allow:

  •  Any type of key (objects, functions, numbers, strings)
  •  Values to be stored in insertion order
  •  Easy size checking

 Creating a Map

 Adding Key-Value Pairs

Use the .set() method:

 Getting Values

console.log(map.get("name")); // Alice
console.log(map.get(1)); // Number Key

 Checking Keys

 Removing Items

 Clear All Items

 Size of a Map

 Iterating Through a Map

Loop through keys and values:


 

Using forEach():

 Useful Methods Summary

MethodDescription
set(key, value)Adds or updates entry
get(key)Returns value for the key
has(key)Checks if key exists
delete(key)Removes key/value
clear()Removes all entries
sizeNumber of items

 Map vs Object

FeatureMapObject
Key typeAny typeString/symbol only
OrderedYesNo guarantee
IterableYesNo (needs conversion)
Size tracking size propertyMust count manually

 Practical Example: Counting Occurrences


 

Output:

Map(3) { 'apple' => 2, 'banana' => 2, 'orange' => 1 }

You may also like...