WeakMap for Private Data in JavaScript

Level 5362 keystrokes

Uses WeakMap to store truly private data associated with class instances.

JavaScript code

// WeakMap stores key-value pairs where keys must be objects
// Keys are weakly held, allowing garbage collection
1const privateData = new WeakMap();
2
3class User {
// Constructor takes public name and private secret
4 constructor(name, secret) {
// name is a public property
5 this.name = name;
// Store secret in WeakMap using 'this' as key
// This data is truly private - not on the object itself
6 privateData.set(this, { secret });
7 }
8
// Method to verify the secret without exposing it
9 checkSecret(guess) {
// Retrieve private data using 'this' as key
// Compare the stored secret with the guess
10 return privateData.get(this).secret === guess;
11 }
12}
13
// Create a user with a secret
14const user = new User("Alice", "password123");
// Public name is accessible
15console.log(user.name);
// Wrong guess returns false
16console.log(user.checkSecret("wrong"));
// Correct guess returns true
17console.log(user.checkSecret("password123"));

Output

Alice
false
true
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.

  • (× 11
  • )× 11
  • .× 10
  • ;× 8
  • "× 8
  • =× 6
  • {× 4
  • }× 4
  • ,× 3

More JavaScript examples at level 5

← JavaScript typing practice