Symbol Usage in JavaScript

Level 4257 keystrokes

Uses Symbol to create unique property keys that won't conflict with other properties.

JavaScript code

// Symbol() creates a unique, immutable identifier
// The string is just a description for debugging
1const ID = Symbol("id");
2const SECRET = Symbol("secret");
3
// Create an object with both regular and Symbol properties
4const user = {
// Regular string property
5 name: "Alice",
// Symbol properties use computed property syntax []
6 [ID]: 12345,
7 [SECRET]: "password123"
8};
9
// Access regular property with dot notation
10console.log(user.name);
// Access Symbol property with bracket notation
11console.log(user[ID]);
// Object.keys() only returns string keys, not Symbols
12console.log(Object.keys(user));
// getOwnPropertySymbols() returns Symbol keys
13console.log(Object.getOwnPropertySymbols(user));

Output

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

  • "× 8
  • (× 8
  • )× 8
  • ;× 7
  • .× 7
  • :× 3
  • [× 3
  • ]× 3
  • =× 3
  • ,× 2

More JavaScript examples at level 4

← JavaScript typing practice