JavaScript Maps

JavaScript Maps

A Map 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

Method Description
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
size Number of items

๐Ÿ†š Map vs Object

Feature Map Object
Key type Any type String/symbol only
Ordered Yes No guarantee
Iterable Yes No (needs conversion)
Size tracking size property Must count manually

โญ Practical Example: Counting Occurrences


 

Output:

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

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *