JavaScript Map - Exercise 1

A Map is a built-in JavaScript object that stores key-value pairs. Unlike plain objects, a Map can use any value as a key, including objects, functions, and primitives.

javascript

// Creating a Map
const myMap = new Map();

console.log(myMap); // Map(0) {}
console.log(typeof myMap); // "object"
console.log(myMap instanceof Map); // true

You create an empty Map by calling the new Map() constructor without any arguments. This creates a Map with no entries and a size of 0.

javascript

// Creating an empty Map
const emptyMap = new Map();

console.log(emptyMap); // Map(0) {}
console.log(emptyMap.size); // 0

You can create a Map with initial values by passing an array of key-value pairs to the constructor. Each inner array should contain two elements: the key and the value.

javascript

// Creating a Map with initial key-value pairs
const userAges = new Map([
  ['Alice', 25],
  ['Bob', 30],
  ['Charlie', 35]
]);

console.log(userAges); // Map(3) { 'Alice' => 25, 'Bob' => 30, 'Charlie' => 35 }
console.log(userAges.size); // 3

Use the .set(key, value) method to add a new key-value pair to a Map. If the key already exists, the value is updated. The method returns the Map itself.

javascript

const fruits = new Map();

// Adding key-value pairs
fruits.set('apple', 5);
fruits.set('banana', 3);
fruits.set('orange', 8);

console.log(fruits); // Map(3) { 'apple' => 5, 'banana' => 3, 'orange' => 8 }

// Updating an existing key
fruits.set('apple', 10);
console.log(fruits.get('apple')); // 10

Use the .get(key) method to retrieve the value associated with a specific key. If the key does not exist, it returns undefined.

javascript

const colors = new Map([
  ['red', '#FF0000'],
  ['green', '#00FF00'],
  ['blue', '#0000FF']
]);

console.log(colors.get('red')); // '#FF0000'
console.log(colors.get('green')); // '#00FF00'
console.log(colors.get('yellow')); // undefined (key does not exist)

Use the .has(key) method to check whether a specific key exists in the Map. It returns true if the key is found and false otherwise.

javascript

const scores = new Map([
  ['Alice', 95],
  ['Bob', 87],
  ['Charlie', 92]
]);

console.log(scores.has('Alice')); // true
console.log(scores.has('Bob')); // true
console.log(scores.has('David')); // false
console.log(scores.has('alice')); // false (case-sensitive)

Use the .delete(key) method to remove a specific key-value pair from a Map. It returns true if the key was found and removed, and false if the key was not found.

javascript

const inventory = new Map([
  ['apples', 50],
  ['bananas', 30],
  ['oranges', 25]
]);

// Remove an existing key
const removed = inventory.delete('bananas');
console.log(removed); // true
console.log(inventory); // Map(2) { 'apples' => 50, 'oranges' => 25 }

// Try to remove a non-existent key
const notFound = inventory.delete('grapes');
console.log(notFound); // false

Use the .size property to get the number of key-value pairs in a Map. Note that .size is a property, not a method, so you do not use parentheses.

javascript

const users = new Map([
  ['user1', 'Alice'],
  ['user2', 'Bob'],
  ['user3', 'Charlie']
]);

console.log(users.size); // 3

// size updates automatically
users.set('user4', 'David');
console.log(users.size); // 4

users.delete('user1');
console.log(users.size); // 3

Use the .clear() method to remove all key-value pairs from a Map at once. After calling .clear(), the Map becomes empty and its .size becomes 0.

javascript

const settings = new Map([
  ['theme', 'dark'],
  ['language', 'en'],
  ['notifications', true]
]);

console.log(settings.size); // 3

// Remove all entries
settings.clear();

console.log(settings.size); // 0
console.log(settings); // Map(0) {}

A Map can use any value as a key, including objects, functions, arrays, and primitives like numbers, strings, and booleans. This is a major advantage over plain objects which only allow strings and symbols as keys.

javascript

const myMap = new Map();

// String key
myMap.set('name', 'Alice');

// Number key
myMap.set(42, 'The answer');

// Object key
const objKey = { id: 1 };
myMap.set(objKey, 'Object value');

// Function key
const fnKey = function() {};
myMap.set(fnKey, 'Function value');

// Array key
const arrKey = [1, 2, 3];
myMap.set(arrKey, 'Array value');

console.log(myMap.size); // 5
console.log(myMap.get(42)); // 'The answer'
console.log(myMap.get(objKey)); // 'Object value'

Maps differ from plain objects in several key ways: Maps can use any value as a key, Maps maintain insertion order, Maps have a .size property, and Maps are optimized for frequent additions and deletions.

javascript

// Plain object: keys are converted to strings
const obj = {};
obj[1] = 'one';
obj['1'] = 'string one';
console.log(Object.keys(obj)); // ['1'] (only one key)

// Map: keys keep their type
const map = new Map();
map.set(1, 'one');
map.set('1', 'string one');
console.log(map.size); // 2 (two different keys)

// Map has built-in size
console.log(map.size); // 2

// Object requires Object.keys()
console.log(Object.keys(obj).length); // 1

Since the .set() method returns the Map itself, you can chain multiple .set() calls together. This provides a concise way to add multiple entries in a single statement.

javascript

// Chaining set() calls
const config = new Map()
  .set('host', 'localhost')
  .set('port', 3000)
  .set('debug', true)
  .set('timeout', 5000);

console.log(config.size); // 4
console.log(config.get('host')); // 'localhost'
console.log(config.get('port')); // 3000

// This is equivalent to:
const config2 = new Map();
config2.set('host', 'localhost');
config2.set('port', 3000);
config2.set('debug', true);
config2.set('timeout', 5000);