What are the practical applications of ES6 WeakMap

0 votes
Can you tell me What are the practical applications of ES6 WeakMap?
Feb 10 in Node-js by Ashutosh
• 27,650 points
99 views

1 answer to this question.

0 votes

Practical Applications of WeakMap:

Private Data Storage:

Store private data for objects that can't be accessed directly, ensuring data security.

const privateData = new WeakMap();

class Person {

  constructor(name) {

    privateData.set(this, { name });

  }

  getName() {

    return privateData.get(this).name;

  }

}

const person = new Person('Alice');

console.log(person.getName()); // Alice

Metadata Association:

Attach extra data (metadata) to objects without modifying them directly.

const metadata = new WeakMap();

const obj = {};

metadata.set(obj, { id: 1, info: "example" });

console.log(metadata.get(obj)); // { id: 1, info: "example" }

Event Listener Management:

Track event listeners to avoid memory leaks when elements are removed.

const listeners = new WeakMap();

const button = document.querySelector('button');

function clickHandler() {

  console.log('Clicked!');

}

listeners.set(button, clickHandler);

button.addEventListener('click', clickHandler);

Caching Results:

Cache computed results to save processing time.

const cache = new WeakMap();

function compute(obj) {

  if (cache.has(obj)) return cache.get(obj);

  const result = obj.value * 2; // Example calculation

  cache.set(obj, result);

  return result;

}

answered Feb 10 by Navya

Related Questions In Node-js

0 votes
1 answer

What are the limitations of React Native?

React Native is a popular framework for ...READ MORE

answered Dec 12, 2024 in Node-js by Navya
143 views
0 votes
1 answer
0 votes
1 answer

What are the implications of using React Router in a React Native application?

React Router is primarily designed for web ...READ MORE

answered 1 day ago in Node-js by anonymous
32 views
0 votes
1 answer

How do I transform an array into an object?

Here are some common approaches: Using Array.prototype.reduce(): Example: const array ...READ MORE

answered Feb 10 in Node-js by Navya
109 views
0 votes
1 answer

How do I set Resharper's language level for ECMAScript 6?

To configure ReSharper to recognize ECMAScript 6 ...READ MORE

answered Feb 10 in Node-js by Navya
103 views
0 votes
1 answer

What is the correct method to clone a JavaScript object?

Cloning a JavaScript object can be achieved ...READ MORE

answered Feb 10 in Node-js by Navya
165 views
0 votes
1 answer

What is the difference between calling "super()" and "super(props)" in React ES6 classes?

Aspect super() super(props) Purpose Calls the parent class constructor without passing ...READ MORE

answered Feb 21 in Node-js by Kavya
106 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP