WeakSet in JavaScript. Code examples open

WeakSet in JavaScript. Code examples

This method is similar to the usual Set. It can also only store unique values, but each element must represent an object.

Let’s create a WeakSet object:

    const weakSet = new WeakSet();

Let’s create a WeakSet object with initial parameters:

    const weakSet = new WeakSet([{ name: "Alexander", age: 33 }, { name: "Timote", age: 25 }]);

To add data to a WeakSet, use the add method:

    const weakSet = new WeakSet();
    weakSet.add({ lang: "English" });
We can only add an object, not scalar values like numbers or strings.

For deletion, the delete() method is used, into which a reference to the object to be deleted is passed:

    const weakSet = new WeakSet();
    const js = { lang: "JavaScript" };
    weakSet.add(js);

    weakSet.delete(js);

The has method allows you to check if an object is in the WeakSet:

    const js = { lang: "JavaScript" };
    const ts = { lang: "TypeScript" };
    const weakSet = new WeakSet([js, ts]);
    console.log(weakSet.has(ts));       // true
Returns true if there is an object

Objects are passed to WeakSet by reference. And when an object ceases to exist for various reasons, it is removed from the WeakSet. So, consider the following example:

    let js = { lang: "JavaScript" };
    let ts = { lang: "TypeScript" };
    
	const weakSet = new WeakSet([js, ts]);

    js = null;

    const timerId = setTimeout(function () {
        console.log(weakSet);   // {{lang: "TypeScript"}}
        clearTimeout(timerId);
    }, 9000);
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation