Symbols Flashcards
What is a symbols for? (2 thing)
identifiers for unique object properties
Symbols are always unique unless otherwise intended.
So we use a symbol to guarantee we’re creating a unique object key.
Basically so we can make properties that will be used by a different library without clashing keys.
Symbols show up in the object properties
t or f
False
But they’re not private. They’re just not obvious.
Why use symbols?
When an object encounters new code, it can be unsafe to have common key names applied.
The symbol as a key protects properties from being altered meeting new code.
let user = { name: "John" }; // Our script uses "id" property user.id = "Our id value"; // ...Another script also wants "id" for its purposes... user.id = "Their id value" // Boom! overwritten by another script!
Create a symbol
let id = Symbol()
What does: let id = Symbol() do?
Assigns a unique long number to id.
It’s can then be passed to an object as a unique key that we can access with id
What is the argument for? let id = Symbol("id");
It’s a description. It’s for debugging mostly
What happens with: let id1 = Symbol("id"); let id2 = Symbol("id");
alert(id1 == id2);
false
The argument is just a description. These are different symbols.
What happens with:
let id = Symbol(“id”);
alert(id);
Error
Symbols don’t auto convert to strings like other data types.
Convert a symbol to a string
Symbol.prototype.toString()
returns something like Symbol(‘description’
What does:
Symbol.prototype.toString()
do?
Returns the symbol like this: Symbol(‘description’)
Return a symbol’s description
Symbol.prototype.description
What does:
Symbol.prototype.description
do?
Return a symbol’s description
Create a hidden property on an object with a symbol
let user = { name: "John" };
let id = Symbol(“id”);
user[id] = 1;
Retrieve an objects hidden property from a symbol:
let user = { name: "John" };
let id = Symbol(“id”);
user[id] = 1;
user[id] = 1;
Symbols take part in For…In loops
t or f
false