in , ,

JavaScript Set and WeakSet

JavaScript Set and WeakSet
JavaScript Set and WeakSet

JavaScript Set and WeakSet

In this tutorial, you will learn about JavaScript Sets and WeakSets with the assistance of examples.

The JavaScript ES6 has presented two new data structures, i.e Set and WeakSet.

Set is like an array that allows us to store numerous items like numbers, strings, objects, and so on In any case, in contrast to an array, a set can’t contain copy values.

Difference between Set and WeakSet in JavaScript

Set

Set data type represents a set of elements (an assortment) and you can iterate through the components of a set in insertion order. Another significant point is that sets are requested arrangements of qualities that contain no duplicate items and are accessed using keys, rather indexes.

It’s additionally worth noting that a component in a set can’t be retrieved using any technique and it can be of any type.

WeakSet

WeakSet are fundamentally equivalent to Set with two significant contrasts:

1 — The values stored in WeakSet can’t be primitive values (Boolean, Number, String, or undefined)

2 — WeakSet is weak: If there is no other reference to an object stored in the WeakSet, it can be garbage collected. Because of this, we can’t iterate over WeakSet items.


Create JavaScript Set

To create a Set, you need to use the new Set() constructor. For example,

// create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}

// Set with multiple types of value
const set2 = new Set([1, 'hello', {count : true}]);
console.log(set2); // Set {1, "hello", {count: true}}

At the point when copy values are passed to a Set object, the copy values are excluded.

// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}

Access Set Elements

You can get to Set components using the values() strategy and check if there is a component inside Set using the has() technique. For instance,

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

// access the elements of a Set
console.log(set1.values()); // Set Iterator [1, 2, 3]

You can use the has() method to check if the component is in a Set. For instance,

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

// check if an element is in Set
console.log(set1.has(1));

Adding New Elements

You can add elements to a Set using the add() method. For instance,

const set = new Set([1, 2]);
console.log(set.values());

// adding new elements
set.add(3);
console.log(set.values());

// adding duplicate elements
// does not add to Set
set.add(1);
console.log(set.values());

Output

Set Iterator [1, 2]
Set Iterator [1, 2, 3]
Set Iterator [1, 2, 3]

Removing Elements

You can use the clear() and the delete() strategy to eliminate elements from a Set.

The delete() strategy eliminates a particular element from a Set. For instance,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// removing a particular element
set.delete(2);
console.log(set.values()); // Set Iterator [1, 3]

The clear() method removes all elements from a Set. For example,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// remove all elements of Set
set.clear();
console.log(set.values()); // Set Iterator []

Iterate Sets

You can iterate through the Set components using the for…of loop or forEach() strategy. The elements are accessed in the insertion request. For instance,

const set = new Set([1, 2, 3]);

// looping through Set
for (let i of set) {
    console.log(i);
}

Output

1
2
3

JavaScript WeakSet

The WeakSet is like a Set. In any case, WeakSet can just contain objects while a Set can contain any data types, for example, strings, numbers, objects, and so on For instance,

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

let obj = {
    message: 'Hi',
    sendMessage: true
}

// adding object (element) to WeakSet
weakSet.add(obj);

console.log(weakSet); // WeakSet {{message: "Hi", sendMessage: true}}

At the point when you attempt to add other data types other than objects, WeakSet throws an error. For instance,

// trying to add string to WeakSet
weakSet.add('hello');

// throws error
// TypeError: Attempted to add a non-object key to a WeakSet
console.log(weakSet);

WeakSet Methods

WeakSets have methods add(), delete(), and has(). For example,

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

const obj = {a:1};

// add to a weakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{a: 1}}

// check if an element is in Set
console.log(weakSet.has(obj)); // true

// delete elements
weakSet.delete(obj);
console.log(weakSet); // WeakSet {}

WeakSets Are Not iterable

Unlike Sets, WeakSets are not iterable. For example,

const weakSet = new WeakSet({a:1});

// looping through WeakSet
for (let i of weakSet) {

    // TypeError
    console.log(i);
}

Mathematical Set Operations

In JavaScript, Set doesn’t provide built-in methods for performing mathematical operations, for example, association, intersection, distinction, and so on Be that as it may, we can create programs to play out those tasks.

Example: Set Union Operation

// perform union operation
// contain elements of both sets
function union(a, b) {
    let unionSet = new Set(a);
    for (let i of b) {
        unionSet.add(i);
    }
    return unionSet
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = union(setA, setB);

console.log(result);

Output

Set {"apple", "mango", "orange", "grapes", "banana"}

Example: Set Intersection Operation

// perform intersection operation
// elements of set a that are also in set b
function intersection(setA, setB) {
    let intersectionSet = new Set();

    for (let i of setB) {
        if (setA.has(i)) {
            intersectionSet.add(i);
        }
    }
    return intersectionSet;
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = intersection(setA, setB);

console.log(result);

Output

Set {"apple"}

Example: Set Difference Operation

// perform difference operation
// elements of set a that are not in set b
function difference(setA, setB) {
    let differenceSet = new Set(setA)
    for (let i of setB) {
        differenceSet.delete(i)
    }
    return differenceSet
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = difference(setA, setB);

console.log(result);

Output

Set {"mango", "orange"}

Example: Set Subset Operation

// perform subset operation
// true if all elements of set b is in set a
function subset(setA, setB) {
    for (let i of setB) {
        if (!setA.has(i)) {
            return false
        }
    }
    return true
}

// two sets of fruits
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['apple', 'orange']);

let result = subset(setA, setB);

console.log(result);

Output

true

JavaScript Sets and WeakSets were introduced in ES6. Some browsers may not support their use. To learn more, visit JavaScript Sets support and JavaScript WeakSets support.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

JavaScript Map

JavaScript Map

JavaScript Destructuring Assignment

JavaScript Destructuring Assignment