How to Compare ES6 Sets for Equality

There is no direct method to compare ES6 Sets for equality in JavaScript. However, you can loop through the contents of the Set, check if any element in one Set exists in the other, and check if their sizes are equal.

Here’s a custom function to compare two ES6 sets for equality.

  1. You can check if the sizes of the two sets are the same. If not, return false.
  2. Loop through the contents of the first Set and check if each element exists in the second Set. If any element is missing, return false.
  3. If both conditions are met, the sets are equal, and the function returns true.

For example:

function areSetsEqual(setA, setB) {
 if (setA.size !== setB.size) {
   return false;

 for (let elem of setA) {
   if (!setB.has(elem)) {
     return false;

  return true;

const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([4, 3, 2, 1]);
const set3 = new Set([1, 2, 3]);

console.log(areSetsEqual(set1, set2));
console.log(areSetsEqual(set1, set3));



This approach ensures that the sets are equal by verifying that all elements in the first Set exist in the second Set and that their sizes match.

Leave a Comment