JavaScript creation date: update date:

Understanding Map, WeakMap, Set, and WeakSet in JavaScript

TL;DR

Map vs. WeakMap

Map is a data structure similar to Object; both store data in key-value pairs. WeakMap is similar to Map in usage, but with two main differences: it only accepts Objects as keys, and these objects can be garbage collected.

Set vs. WeakSet

Set is a data structure similar to an array, but all elements inside are unique with no duplicates. WeakSet is similar to Set in usage, but with two main differences: elements can only be Objects and these objects can be garbage collected.

Map

Introduction

Map is a data structure similar to Object; both store data in key-value pairs. In JavaScript, Map is a constructor function that creates Map instances using new Map().

Common Operations

Common Iteration Methods

The iteration order corresponds to the insertion order of elements.

WeakMap

Similar to Map in usage, but with two main differences:

Set

Introduction

Set is a data structure similar to an array, but all elements inside are unique with no duplicates. In JavaScript, Set is a constructor function that creates Set instances using new Set().

Common Operations

WeakSet

Similar to Set in usage, but with two main differences:

References

What Is the Difference Between Set, Map, WeakSet, and WeakMap in JavaScript?| ExplainThis