Skip to content

Instantly share code, notes, and snippets.

@Ladvace
Last active May 31, 2022 09:31
Show Gist options
  • Save Ladvace/47362347fd015f42fa7e36a68bf82f98 to your computer and use it in GitHub Desktop.
Save Ladvace/47362347fd015f42fa7e36a68bf82f98 to your computer and use it in GitHub Desktop.
let obj = {}
const symbol1 = Symbol("a")
const symbol2 = Symbol("a")
const sharedSymbol = Symbol.for('b')
obj[symbol1] = 'a'
obj[sharedSymbol] = 'b'
obj['c'] = 'c'
obj.d = 'd'
obj[symbol1] // 'a'
obj[symbol2] // undefined, symbol1 and symbol2 are two different symbols, "a" it's just a description and not an identifier
obj[sharedSymbol] // 'b'
obj[Symbol.for('b')] // 'b', Symbol.for access the symbol in the symbol registry, so the symbol it's always the same
// in this case 'b' it's used as unique key and not just as description
for (let i in obj) {
console.log(i) // logs "c" and "d", symbols are not enumerable in for...in so they are not gonna be printed
}
for(let i of Object.getOwnPropertySymbols(obj) ) {
console.log(obj[i]); // instead you can use getOwnPropertySymbols that returns an array of Symbols
}
JSON.stringify(obj) // {c: 'c', d: 'd'}, Symbol-keyed properties will be completely ignored when using JSON.stringify()
// you could use this a trick to save only same values in a DB and leave the others locally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment