WeakMap in JavaScript. Code examples open

WeakMap in JavaScript. Code examples

WeakMap represents the evolution of the Map collection. A feature of WeakMap is that all of its elements must represent objects. In this case, the keys must represent objects.

Let’s create a WeakMap object:

    const weakMap1 = new WeakMap();

Let’s create a WeakMap with data initialization:

    let key1 = { key: 1 };
    let key2 = { key: 2 };
    let value1 = { name: "Tom" };
    let value2 = { name: "Sam" };

    const weakMap = new WeakMap([[key1, value1], [key2, value2]]);

The set() method is used to add new objects or change old ones:

    let key1 = { key: 1 };
    let key2 = { key: 2 };
    let value1 = { name: "Tom" };
    let value2 = { name: "Sam" };

    const weakMap2 = new WeakMap([[key1, value1]]);
    weakMap2.set(key2, value2);
    weakMap2.set(key1, { name: "Kate" });
    console.log(weakMap2.get(key1));    //{name: "Kate"}
    console.log(weakMap2.get(key2)); 

To get objects by key from WeakMap, the get() method is used:

    let key1 = { key: 1 };
    let key2 = { key: 2 };
    let value1 = { name: "Tom" };
    let value2 = { name: "Sam" };

    const weakMap2 = new WeakMap([[key1, value1], [key2, value2]]);
    console.log(weakMap2.get(key1));  // {name: "Tom"}

The has method allows you to check for the existence of an element by a specific key. The method returns true if the element is present:

    let key1 = { key: 1 },
        key2 = { key: 2 };
    let value1 = { name: "Tom" },
        value2 = { name: "Sam" };

    const weakMap2 = new WeakMap([[key1, value1]]);
    console.log(weakMap2.has(key1));    // true
    console.log(weakMap2.has(key2));    // false 

The delete() method is used to delete an element by key:

    let key1 = { key: 1 },
        key2 = { key: 2 };
    let value1 = { name: "Tom" },
        value2 = { name: "Sam" };

    const weakMap2 = new WeakMap([[key1, value1], [key2, value2]]);
    console.log(weakMap2.has(key1));    // true
    weakMap2.delete(key1);
    console.log(weakMap2.has(key1));    // false

!Objects are passed to WeakMap by reference!

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