Map Data Structure in JavaScript

Level 4266 keystrokes

This demonstrates using Map to store key-value pairs and iterate over them.

JavaScript code

// Create a new Map (key-value collection)
// Unlike objects, keys can be any type
1const scores = new Map();
2
// set() adds or updates a key-value pair
3scores.set("Alice", 95);
4scores.set("Bob", 87);
5scores.set("Carol", 92);
6
// get() retrieves the value for a key
7console.log(scores.get("Alice"));
// has() checks if a key exists
8console.log(scores.has("Dave"));
// size property returns the number of entries
9console.log(scores.size);
10
// forEach iterates over entries
// Callback receives (value, key, map)
11scores.forEach((score, name) => {
12 console.log(`${name}: ${score}`);
13});

Output

95
false
3
Alice: 95
Bob: 87
Carol: 92
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 12
  • )× 12
  • .× 11
  • "× 10
  • ;× 9
  • ,× 4
  • {× 3
  • }× 3
  • `× 2
  • =× 2

More JavaScript examples at level 4

← JavaScript typing practice