Back to Freecodecamp

What Is the Map Object, and How Does It Differ from WeakMaps?

curriculum/challenges/english/blocks/lecture-working-with-maps-and-sets/6733dd694f91d61a5272b4ac.md

latest5.7 KB
Original Source

--description--

In JavaScript, a Map is a built-in object that stores key-value pairs, similar to an object. However, it differs from standard JavaScript objects by allowing keys of any type, including objects and functions.

A WeakMap is a collection of key-value pairs, similar to a Map, but it uses weak references for its keys. The keys must be objects, while the values can be of any type.

Think of the relationship between a WeakMap and a Map as similar to the relationship between a WeakSet and a Set, as you learned in the previous lesson.

To create a Map, you use the Map() constructor prepended with the new keyword:

js
const myFirstMap = new Map();

You can initialize the Map with values:

js
const myTreesMap = new Map([
 [{ type: 'deciduous' }, 'Maple tree'],
 [['forest', 'grove'], 'Pine tree'],
 [42, 'Oak tree'],
 [true, 'Birch tree'],
 [function() { return 'I am a function key'; }, 'Willow tree'],
]);

If you didn't initialize the Map with values, you can use the set() method to add them:

js
const myTreesMap = new Map();
myTreesMap.set({ type: 'deciduous' }, 'Maple tree');
myTreesMap.set([1, 2], 'Pine tree');
myTreesMap.set(42, 'Oak tree');
myTreesMap.set(true, 'Birch tree');
myTreesMap.set(function() { return "I'm a function key"; }, 'Willow tree');

console.log(myTreesMap);

Here's what a Map looks like in the console:

js
/*
Map(5) {{…} => 'Maple tree', Array(2) => 'Pine tree', 42 => 'Oak tree', true => 'Birch tree', ƒ => 'Willow tree'}
  [[Entries]]
    0:{Object => "Maple tree"}
      key: {type: 'deciduous'}
      value: "Maple tree"
    1:{Array(2) => "Pine tree"}
      key: (2)
      value: "Pine tree"
    2:{42 => "Oak tree"}
      key: 42
      value: "Oak tree"
    3:{true => "Birch tree"}
      key: true
      value: "Birch tree"
    4:{function () { return "I'm a function key"; } => "Willow tree"}
      key: f ()
      value: "Willow tree"
    size: 5
    [[Prototype]]: Map
*/

Other methods you can use to work with a Map are:

  • get(key) to retrieve the value associated with the specified key.
  • has(key) to check if a key exists in the Map.
  • delete(key) to remove a key-value pair from the Map.
  • clear() to remove all key-value pairs.
  • entries() to check the entries of the Map (it returns the entries in a MapIterator).
  • forEach() to loop through the entries of the Map.
  • size to indicate the number of key-value pairs in the Map.

There's a WeakMap() constructor you can use to create a WeakMap:

js
const myFirstWeakMap = new WeakMap();

The set(), get(), has(), and delete() methods are all available for use with a WeakMap as well. For example here's how you can assign items to the Map with the set() method:

js
const myTreeWeakMap = new WeakMap();

myTreeWeakMap.set({ id: 1 }, 'Maple tree');
myTreeWeakMap.set({ id: 2 }, 'Pine tree');
myTreeWeakMap.set({ id: 3 }, 'Oak tree');
myTreeWeakMap.set({ id: 4 }, 'Birch tree');
myTreeWeakMap.set({ id: 5 }, 'Willow tree');

console.log(myTreeWeakMap);

Here's what a WeakMap looks like in the console:

js
/*
WeakMap {{…} => 'Willow tree', {…} => 'Maple tree', {…} => 'Pine tree', {…} => 'Oak tree'}
  [[Entries]]
    No properties
  [[Prototype]]: WeakMap
*/

Here are the differences between a Map and a WeakMap:

FeatureMapWeakMap
Key TypeKeys can be of any data type, including strings, numbers, objects, or even functions.Keys must be objects.
Use CaseUse a Map when you need to associate data with any type of key.Use a WeakMap when you only need to associate data with objects.
IterationYou can loop through a Map using forEach(), keys(), values(), or entries().A WeakMap is not iterable.
Size PropertyMap has a size property to get the number of key-value pairs.WeakMap does not have a size property.

In the table above, you can see the differences summarized including the key type, use case, iteration and size property. Please take a moment to read the content of this table to learn more about their differences.

--questions--

--text--

Which of these differentiates a Map from a WeakMap in JavaScript?

--answers--

A Map allows only objects as keys, while a WeakMap allows keys of any type.

--feedback--

Think about the key types allowed and how the references are handled.


A Map has weak references to keys, while a WeakMap does not.

--feedback--

Think about the key types allowed and how the references are handled.


A Map allows keys of any type, while a WeakMap only allows objects as keys.


A Map and a WeakMap function exactly the same.

--feedback--

Think about the key types allowed and how the references are handled.

--video-solution--

3

--text--

Which property lets you know the number of items in a Map?

--answers--

length

--feedback--

Think about the property that measures the number of entries in a Map.


count

--feedback--

Think about the property that measures the number of entries in a Map.


total

--feedback--

Think about the property that measures the number of entries in a Map.


size

--video-solution--

4

--text--

Which method lets you add an item to a Map and a WeakMap?

--answers--

add()

--feedback--

Think about the method specifically used for adding key-value pairs to a Map.


push()

--feedback--

Think about the method specifically used for adding key-value pairs to a Map.


set()


insert()

--feedback--

Think about the method specifically used for adding key-value pairs to a Map.

--video-solution--

3