WeakMap Private Data in JavaScript

Level 5347 keystrokes

WeakMap can store private data associated with objects without preventing garbage collection.

JavaScript code

// WeakMap stores private data for instances
1const privateData = new WeakMap();
// Define Person class
2class Person {
// Constructor takes name and age
3 constructor(name, age) {
// Store private data using instance as key
4 privateData.set(this, { name, age });
5 }
// Getter method for name
6 getName() {
// Retrieve name from private data
7 return privateData.get(this).name;
8 }
// Getter method for age
9 getAge() {
// Retrieve age from private data
10 return privateData.get(this).age;
11 }
12}
// Create a Person instance
13const person = new Person("Alice", 30);
// Access name through method
14console.log(person.getName());
// Access age through method
15console.log(person.getAge());
// Object.keys returns []: name and age are not properties of the instance
16console.log(Object.keys(person));

Output

Alice
30
[]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 14
  • )× 14
  • .× 11
  • ;× 8
  • {× 5
  • }× 5
  • ,× 4
  • "× 2
  • =× 2

More JavaScript examples at level 5

← JavaScript typing practice