JavaScript WeakMap set() method - JavaScript Tutorial

JavaScript WeakMap set() method

BLUF: This tutorial on JavaScript WeakMap set() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript WeakMap set() method

Understanding JavaScript WeakMap set() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The set method of the JavaScript WeakMap is utilized to insert or modify an element within a WeakMap object by associating it with a specific key-value pair. It is essential that each value is linked to a distinct key, which must be an object.

Syntax

The syntax for the set method is depicted as follows:

Example

weakMapObj.set(key,value)

Parameter

key - It represents the key to be added.

value - It represents the value to be added.

Return

The WeakMap object.

JavaScript WeakMap set method example

In this section, we will explore the set function by examining a variety of examples.

Example 1

Let’s examine an example of how to insert elements into a WeakMap object.

Example

<script>

var wm = new WeakWeakMap();

var obj1 = {};

var obj2 = {};

var obj3= {};

wm.set(obj1, "jQuery");

wm.set(obj2, "AngularJS");

wm.set(obj3,"Bootstrap");

document.writeln(wm.get(obj1)+"<br>");

document.writeln(wm.get(obj2)+"<br>");

document.writeln(wm.get(obj3));

</script>

Output:

Output

jQuery

AngularJS

Bootstrap

Example 2

Let’s examine an illustration of how to incorporate elements into a WeakMap object using a chainable format.

Example

<script>

var wm = new WeakMap();

var obj1 = {};

var obj2 = {};

var obj3= {};

wm.set(obj1, "jQuery").set(obj2, "AngularJS").set(obj3,"Bootstrap");

document.writeln(wm.get(obj1)+"<br>");

document.writeln(wm.get(obj2)+"<br>");

document.writeln(wm.get(obj3));

</script>

Output:

Output

jQuery

AngularJS

Bootstrap

Example 3

In this illustration, we will analyze the outcome when varying values are incorporated into the same object.

Example

<script>

var wm = new WeakMap();

var obj1 = {};

var obj2 = {};

wm.set(obj1, "jQuery");

wm.set(obj2, "AngularJS");

wm.set(obj2,"Bootstrap");

document.writeln(wm.get(obj1)+"<br>");

document.writeln(wm.get(obj2)+"<br>");

document.writeln(wm.get(obj2));

</script>

Output:

Output

jQuery

Bootstrap

Bootstrap

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience