The Wayback Machine - https://web.archive.org/web/20240914143557/https://www.geeksforgeeks.org/javascript-weakmap/
Open In App

JavaScript WeakMap

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A WeakMap in JavaScript is a collection where keys can only be objects or non-registered symbols. It allows values of any type and doesn’t prevent the keys from being garbage collected, making its values eligible for garbage collection when their keys are collected. 

Syntax

new WeakMap()
new WeakMap(iter)

Parameter: It has only one optional parameter.

  • iter: It is an iterable JavaScript object that implements the @@iterator method. It contains two elements where the first is key and the second is value.

Example 1: In this example The myGeeks function creates a WeakMap looseMap, sets objects as keys with names, assigns values, and checks if it has a specific key. Outputs the map and checks for presence of Ram.

JavaScript
function myGeeks() {
    let looseMap = new WeakMap();
    let Ram = {name};
    let Raj = {name};
    let Rahul = {name};
    looseMap.set(Ram, "Ram");
    looseMap.set(Raj, "Raj");
    looseMap.set(Rahul, "Rahul");
    console.log(looseMap);
    console.log(looseMap.has(Ram))
}
myGeeks();

Output:

WeakMap {{…} => 'Raj', {…} => 'Rahul', {…} => 'Ram'}
true

Example 2: In this example, we creates a WeakMap looseMap, sets an object Ram as a key with a value, nullifies Ram, and logs looseMap at different intervals.

JavaScript
let looseMap = new WeakMap();
let Ram = { name };
looseMap.set(Ram, "Ram");
console.log(looseMap);
Ram = null;
console.log(looseMap)
setTimeout(function () {
    console.log(looseMap);
}, 300)

Output: As the reference is removed from the memory so the value in looseMap are garbage collected

WeakMap {{…} => 'Ram'}
WeakMap {{…} => 'Ram'}
WeakMap {}

Supported Browsers:

We have a complete list of Javascript WeakMap methods, to check those please go through this JavaScript WeakMap Complete Reference article.

JavaScript WeakMap – FAQs

What is a WeakMap in JavaScript?

A WeakMap is a collection of key/value pairs where the keys are objects and the values can be arbitrary values. The primary feature of a WeakMap is that it holds “weak” references to the keys, meaning that if there are no other references to the key object, it can be garbage collected.

How do you create a WeakMap?

You can create a WeakMap using the WeakMap constructor.

What are the main differences between Map and WeakMap?

  • Key Type: Map keys can be of any type, while WeakMap keys must be objects.
  • Garbage Collection: WeakMap holds weak references to keys, allowing them to be garbage collected, whereas Map holds strong references.
  • Iterability: Map is iterable, meaning you can loop through its entries. WeakMap is not iterable, and you cannot get a list of its keys or values.

How do you set and get values in a WeakMap?

To set a value in a WeakMap, you use the set method, and to get a value, you use the get method.

Can you use primitive values as keys in a WeakMap?

No, WeakMap keys must be objects. Using a primitive value (like a string, number, or boolean) will result in a TypeError.

How do you check if a WeakMap contains a specific key?

You can use the has method to check if a WeakMap contains a specific key.


Previous Article
Next Article

Similar Reads

JavaScript weakMap delete() Method
The weakMap.delete() is an inbuilt function in JavaScript which is used to delete a particular element from an object WeakMap. Syntax: weakMap.delete(key); Parameters: It accepts a parameter "key" which is the key of the element which is going to be deleted from the object weakMap. Return values: It returns true if that element has been deleted fro
2 min read
JavaScript weakMap get() Method
The Javascript weakMap.get() is an inbuilt function in JavaScript that is used to return a particular element from an object WeakMap. Syntax: weakMap.get(key);Parameters: It accepts a parameter "key" which is the key of the element which is going to be returned from the object weakmap. Return values: It returns the element which is associated with
2 min read
JavaScript weakMap has() Method
The Javascript weakMap.has() is an inbuilt function in JavaScript that is used to return a boolean value which indicates whether an element with a particular key is present in the weakmap object or not. Syntax: weakMap.has(key);Parameters: It accepts a parameter 'key' which is the key of the element which is going to be tested for presence in the o
2 min read
JavaScript weakMap set() Method
The weakMap.set() is an inbuilt function in JavaScript which is used to set a new element with a particular key and value to a WeakMap object. Syntax: weakMap.set(key, value); Parameters: It takes parameters "key" which is the key of the element which is to set to the WeakMap object and parameter "value" is the value of the element to set to the We
2 min read
JavaScript WeakMap Reference
JavaScript WeakMap object in JavaScript is used to store the collection of objects (key-value pairs) in which keys are weakly referenced. The major difference between a WeakSet with a set is that a WeakSet is a collection of objects and not values of some particular type. Syntax: WeakMap.function(); Example: Below is the example of weakMap.get() me
2 min read
JavaScript WeakMap() Constructor
The WeakMap() Constructor produces WeakMap objects that are a key/value pair array in which the key is referenced weakly. The keys should be objects and the values could be arbitrary. The difference between Map and WeakMap is that keys must be objects and are only weakly referenced. This means that if there are no other strong references to the key
2 min read
How to understand WeakMap in JavaScript ?
The WeakMap object stores key/value pairs. The keys should be objects, and also the value may be anything. In JavaScript, a map API may be engineered with 2 arrays, one for keys and one for values that are shared by the four API functions. Setting parts on this map would entail at the same time inserting a key and value onto the top of every one of
3 min read
What is the difference between Map and WeakMap in JavaScript ?
In this article, we will talk about the difference between Map and WeakMap which are introduced by ES6. Javascript object supports only one key object. For supporting multiple key objects, Then Map comes on this path. Map: A Map is an unordered list of key-value pairs where the key and the value can be of any type like string, boolean, number, etc.
4 min read
What is the use of a WeakMap object in JavaScript ?
What is a WeakMap? A WeakMap is a collection of key/value pairs where the keys are objects and values are any JavaScript object. It is similar to Map with some differences: It is not enumerable and the keys are private in nature.Allows garbage collection of any values if keys are not referenced from somewhere other than a WeakMap.Only objects are a
3 min read
JavaScript WeakMap constructor Property
JavaScript WeakMap constructor property is used to return the WeakMap constructor function for the object. The function returned by this property is just the reference, not the actual WeakMap. It is an object property of JavaScript and can be used with Strings, Numbers, etc. Syntax: weakset.constructor Return Type: WeakMap() { [native code] } Below
1 min read
What is a WeakMap Object in JavaScript ?
WeakMap is a collection of key-value pairs where keys must be objects, and values can be any values. Unlike a regular Map, it holds weak references to keys, allowing them to be garbage-collected if no other references exist. It is often used to associate private data with objects without causing memory leaks and lacks methods for direct iteration t
1 min read
WeakSet vs WeakMap in JavaScript
In JavaScript, there are two types of references strong and weak. The WeakSet and WeakMap are called weak references. Since these are weak references they do not prevent garbage collection if they are the only reference to the object in the memory. These objects are rarely used but are useful when we want memory usage to be automatically managed. J
2 min read
What is WeakMap in ES6 ?
WeakMap is a new Data Structure or Collection introduced in ES6. WeakMaps allows you to store a collection of Key-Value pairs. It adopts the same properties of Map. The Major difference is that keys of WeakMap cannot be a primitive data type. The keys must be of type object and values can be of any data type. Another major difference is that the ke
2 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &&:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How can JavaScript codes be hidden from old browsers that do not support JavaScript ?
Nowadays all modern browsers support JavaScript, however, older browsers did not support JavaScript. In this article, we will learn how we can hide JavaScript code from running in older browsers. Approach: After opening the <script> tag, we will use a one-line HTML style comment without any closing character ( <!-- ). We will then write th
2 min read
How are the JavaScript window and JavaScript document different from one another?
What is a JavaScript window? The window is at a root/top level at the JavaScript object hierarchy. It is a global/root object in JavaScript and it is the root object of the Document object model(DOM); What is a JavaScript document? A document is an object inside the window object and we use a document object for manipulation inside the document. Th
3 min read
Explore the concept of JavaScript Function Scope and different types of JavaScript Functions
JavaScript is based on functional programming. Therefore, functions are fundamental building blocks of JavaScript. So the function is called first-class citizens in JavaScript. Syntax: Define a functionfunction functionName(parameters) { // SET OF STATEMENTS } Call a functionfunctionName(arguments); The function execution stops when all the stateme
10 min read
Which href value should we use for JavaScript links, "#" or "javascript:void(0)" ?
In this article, we will know which "href" should be used for JavaScript when we can use "#" or "javascript:void(0)". Let us understand it. Using the '#' value: The # is a fragment identifier used to refer to a specific section of the same document. When a user clicks a link with a # href, the browser will scroll to that section of the page specifi
3 min read
How to include a JavaScript file in another JavaScript file ?
In native JavaScript, before ES6 Modules 2015 was introduced had no import, include, or require functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules, there are so many different approa
3 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the length of a linked list easily. Use the below approa
3 min read
Article Tags :