CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

JavaScript - WeakMap

JavaScript - The WeakMap Object

AWeakMapobject in JavaScript is a collection of key-value pairs where the keys are weakly referenced. The WeakMap keys must be objects or non-registered symbols, and values are of any arbitrary JavaScript type.

The WeakMap is similar to the JavaScript Map. The main difference between the WeakMap and Map data structure is that the WeakMap data structure uses the objects as a key only, but Map can use other data types also as a key.

If you use the value of another data type as a key of a WeakMap except the object, it gives the Types error.

Syntax

You can follow the syntax below to use the WeakMap in JavaScript βˆ’

JAVASCRIPT CODE
const weak_map = new WeakMap();

In the above syntax, we used the β€˜new’ keyword with a WeakMap() function to create a new instance of the WeakMap.

The WeakMap provides methods to set, get, and delete the key-value pairs from the WeakMap. Here, we have listed the properties and methods of the WeakMap.

WeakMap Properties

Here is a list of the properties of WeakMap and their description βˆ’

Sr.No.Name & Description1constructorTo get a constructor function of a WeakMap.

WeakMap Methods

Here is a list of the methods associated with WeakMap object and their description βˆ’

Sr.No.Name & Description1delete()To delete a single key-value pair from the WeakMap.2get()To get values related to the specific object.3has()Check whether a particular object exists as a key exists in the WeakMap.4set()To insert the key-value pair in the WeakMap.

WeakMap Constructor()

Following is the WeakMap constructor in JavaScript βˆ’

Sr.No.Name & Description1WeakMap()To create a WeakMap object.

Examples

Example: Inserting key-value pair to the WeakMap

In the example below, we have defined the WeakMap using the constructor function. After that, we used the set() method to set the laptop object as a key and its price as a value.

At last, we used the get() method to get the value related to the β€˜laptop’ key.

Preview

Output

JAVASCRIPT CODE
The laptop price is: 100000

If we execute the program, it returns the value related to the β€œlaptop” key, i.e. β€œ10000”.

Example: Deleting key-value pair from the WeakMap

In the example below, we have inserted the key-value pair in the WeakMap using the set() method.

After that, we used the delete() method to delete the key-value pair from the WeakMap. After deleting the key-value pair when you access it, the WeakMap returns undefined, as you can see in the output.

Noteβˆ’ WeakMaps are not iterable in JavaScript.

Preview

Output

JAVASCRIPT CODE
The laptop price is: 100000
The laptop price after deletion is: undefined

It returns β€œundefined” as the key-value is deleted from the WeakMap.

WeakMaps are not iterable in JavaScript