Wednesday, July 10, 2024

New JavaScript Set methods

New JavaScript Set methods

New JavaScript Set methods



New JavaScript Set methods are arriving! Since Firefox 127, these methods are available in most major browser engines, which means you won't need a polyfill to make them work everywhere.

This article is a good read for people who are new to Set in JavaScript and are looking to find out how to use these new JavaScript methods. I'll highlight some advantages of using these methods with basic examples to show why you might reach for these instead of building your own implementations.

What's new in Set methods?

For those of you looking for the TL;DR, here's the gist of new methods that have cross-browser support:

  • intersection() returns a new set with elements in both this set and the given set.
  • union() returns a new set with all elements in this set and the given set.
  • difference() returns a new set with elements in this set but not in the given set.
  • symmetricDifference() returns a new set with elements in either set, but not in both.
  • isSubsetOf() returns a boolean indicating if all elements of a set are in a specific set.
  • isSupersetOf() returns a boolean indicating if all elements of a set are in a specific set.
  • isDisjointFrom() returns a boolean indicating if this set has no elements in common with a specific set.

If you've read (or skimmed) through the above list and are confused, don't worry, we'll describe what they do in the following sections. Each of these methods are used to check what the contents of sets are compared to the contents of another specific set.

What is a JavaScript Set?

A set is similar to an Array, except that each value can only be stored once. For example, we can take a list of items, add them all to a set, and then inspect the results of the set. The list on the right is the contents of the <ol> list on the left, but converted to a set. We have all duplicates removed from the list because we're guaranteed that a set is unique:

Semiconductor Recycling: Addressing E-Waste Challenges

Semiconductor Recycling: Addressing E-Waste Challenges The increasing demand for electronic devices, from smartphones to electric cars, has ...