Skip to content

JavaScript‌ ‌Map‌ ‌and‌ ‌Set

Introduction to JavaScript Maps

What is a JavaScript Map?

In JavaScript, a Map is a collection that stores key-value pairs. It allows the use of various data types as keys and maintains the order of its entries, differentiating it from regular objects that only support strings and symbols as keys.

Creating and Manipulating Maps

To create a Map, use new Map(). It supports several methods for data manipulation:

  • map.set(key, value): Adds a key-value pair.
  • map.get(key): Retrieves the value associated with a key.
  • map.has(key): Checks if a key exists.
  • map.delete(key): Removes a key-value pair.
  • map.clear(): Clears the Map.
  • map.size: Returns the number of key-value pairs.

Code Example:


Output appears here after Run.

Iterating Over Maps

Maps can be iterated in various ways: - Using map.keys(), map.values(), and map.entries().

  • Using for...of loops.
  • Using map.forEach() method.

Code Example:


Output appears here after Run.

Understanding JavaScript Sets

What is a JavaScript Set?

A Set in JavaScript is a collection of unique values. Unlike an array, each element can only occur once in a Set.

Working with Sets

To work with Sets:

  • Create a Set using new Set(iterable).
  • Add an element using set.add(value).
  • Check for an element using set.has(value).
  • Remove an element using set.delete(value).
  • Determine the number of elements using set.size.
  • Clear a Set using set.clear().

Code Example:


Output appears here after Run.

Iterating Over Sets

Sets can be iterated using:

  • for...of loops.
  • set.forEach() method, which provides access to each value in the Set.

Code Example:


Output appears here after Run.

INFO

In addition to Map and Set, JavaScript also provides WeakMap and WeakSet, which manage memory differently by allowing their elements to be garbage-collected. Learn more about these specialized collections on our JavaScript WeakMap and WeakSet page.

Conclusion

JavaScript Maps and Sets offer powerful data structures for managing unique collections and key-value pairs. Understanding their functionalities and appropriate use cases enhances your JavaScript coding skills, leading to more efficient and effective code development.

Remember, JavaScript is a versatile language, and mastering these advanced concepts is crucial for tackling complex programming challenges. Keep practicing and exploring to deepen your understanding of JavaScript's capabilities.

Practice

What are some properties of JavaScript Map and Set?

Dual-run preview — compare with live Symfony routes.