Hidden properties with Symbol
Learn that Symbol properties are hidden and do not appear in for...in.
Symbol keys
A symbol can be used as a property key of an object. Unlike string keys, symbol keys are hidden from for...in and Object.keys(); they also disappear during serialization.
This makes them ideal for storing internal metadata that should not appear in normal iteration. To access symbol keys, use Object.getOwnPropertySymbols(), because Object.keys returns only string keys.
Object.getOwnPropertySymbols
To reach symbol-keyed properties, use Object.getOwnPropertySymbols(obj). This method returns an array of all symbol keys on the object.
String and symbol keys live in separate slots: Object.keys() returns strings only, and Object.getOwnPropertySymbols() returns symbols only. Together they give the full picture of an object.
Exercise Hide and reveal a symbol property
Create a symbol named id. Add a string key name: 'Alex' and a symbol key [id]: 101 to the user object. Use for...in to walk user and log the keys (only name should appear). Then log the symbol keys using Object.getOwnPropertySymbols(user).
Show example solution
const id = Symbol('id');
const user = {
name: 'Alex',
[id]: 101
};
for (let key in user) {
console.log(key);
}
console.log(Object.getOwnPropertySymbols(user));
Test yourself
-
If an object has a symbol-keyed property, what does a for...in loop do?
- It iterates over the symbol keys too
- It skips the symbol keys
- It throws an error
- It iterates over only the symbol keys
Show answer
It skips the symbol keys — Correct. for...in only iterates over string and number keys; symbol keys are skipped.
-
Use a symbol as a key
const secret = Symbol('id'); const user = { name: 'Alex', [____]: 42 };Show answer
const secret = Symbol('id'); const user = { name: 'Alex', [secret]: 42 }; -
Symbol key properties
- Symbol key
- Hidden from for...in
- Object.keys()
- String keys only
- Object.getOwnPropertySymbols()
- Returns symbol keys
- Symbol property
- Lives in a separate slot