Symbol Unique Keys in JavaScript

Level 5308 keystrokes

Symbols create unique property keys that don't appear in regular object enumeration methods.

JavaScript code

// Create unique symbol for ID
1const ID = Symbol("id");
// Create unique symbol for SECRET
2const SECRET = Symbol("secret");
// Object with regular and symbol properties
3const user = {
// Regular string property
4 name: "Alice",
// Symbol property - hidden from most iterations
5 [ID]: 12345,
// Another symbol property
6 [SECRET]: "abc123"
7};
// Access regular property
8console.log(user.name);
// Access symbol property using bracket notation
9console.log(user[ID]);
// Object.keys only shows regular keys
10console.log(Object.keys(user));
// Get all symbol properties
11console.log(Object.getOwnPropertySymbols(user));
// Use the first symbol (ID) as a key: 12345
12console.log(user[Object.getOwnPropertySymbols(user)[0]]);

Output

Alice
12345
[ 'name' ]
[ Symbol(id), Symbol(secret) ]
12345
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.

  • (× 10
  • )× 10
  • .× 9
  • ;× 8
  • "× 8
  • [× 5
  • ]× 5
  • :× 3
  • =× 3
  • ,× 2

More JavaScript examples at level 5

← JavaScript typing practice