JavaScript WeakMap get() method - JavaScript Tutorial

JavaScript WeakMap get() method

BLUF: This tutorial on JavaScript WeakMap get() 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 get() method

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

The get method of the WeakMap in JavaScript retrieves the value associated with a particular key from a WeakMap instance.

Syntax

The syntax for the get method can be illustrated as follows:

Example

WeakMapObj.get(key)

Parameter

key - The key to be searched.

Return

The value of the specified key.

JavaScript WeakMap get method example

In this section, we will explore the get method by examining a range of examples.

Example 1

Let's see a simple example of get method.

Example

<script>

var wm = new WeakMap();

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 a scenario to establish the outcome when a WeakMap object does not include the specified key.

Example

<script>

var wm = new WeakMap();

var obj1 = {};

var obj2 = {};

var obj3= {};

wm.set(obj1, "jQuery");

wm.set(obj2, "AngularJS");

wm.set(obj3,"Bootstrap");

document.writeln(wm.get());//returns undefined

</script>

Output:

Output

undefined

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