The JavaScript weakMap set method is used to set a new element with a specified key and value to a WeakMap object.
Syntax
weakMap.set(key, value);
Parameters
- key: It represents the object that will be used as the key in the WeakMap.
- value: It corresponds to the value associated with the key in the WeakMap.
Return Value
It returns a weakMap object.
Example 1: How to Use JavaScript weakMap set() Method
let weakMap = new WeakMap();
let key1 = {};
let key2 = {};
weakMap.set(key1, "Taylor Swift");
weakMap.set(key2, "Selena Gomez");
console.log(weakMap.get(key1));
console.log(weakMap.get(key2));
Output
Taylor Swift
Selena Gomez
Example 2: WeakMap object in chainable form
let weakMap = new WeakMap();
let key1 = {};
let key2 = {};
weakMap.set(key1, "Taylor Swift").set(key2, "Selena Gomez");
console.log(weakMap.get(key1));
console.log(weakMap.get(key2));
Output
Taylor Swift
Selena Gomez
Browser Compatibility
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
That’s it!
Related posts
JavaScript WeakMap get() Method
JavaScript WeakMap has() Method
JavaScript WeakMap delete() Method

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.