Symbol Type Flashcards
By specification, only two primitive types may serve as object property keys:
string type,
symbol type.
A _______ represents a unique identifier.
“symbol”
let id1 = Symbol(“id”);
let id2 = Symbol(“id”);
alert(id1 == id2); // Returns and why?
false
Symbols are guaranteed to be unique.
let id1 = {};
let id2 = {};
alert(id1 == id2); returns
false
let id1 = {};
let id2 = id1;
alert(id1 == id2); returns?
true
Symbols do or don’t auto-convert to a string
don’t
let id = Symbol(“id”);
alert(id); // returns?
TypeError: Cannot convert a Symbol value to a string
let id = Symbol(“id”);
alert(id.toString()); // returns
Symbol(id), now it works
let user = { // belongs to another code
name: “John”
};
let id = Symbol(“id”);
// assign id to user object
alert( user[id] ); // we can access the data using the symbol as the key
user[id] = 1;
If we want to use a symbol in an object literal {…}
we need square brackets around it.
let id = Symbol(“id”);
let user = {
name: “John”,
// code here
};
what is correct [id]: 123 or [“id”]:123 and why?
That’s because we need the value from the variable id as the key, not the string “id”.
Symbolic properties do not participate in_________ loop
for..in loop.
let id = Symbol(“id”);
let user = {
name: “John”,
age: 30,
[id]: 123
};
for (let key in user) alert(key); // returns?
name, age (no symbols)
let id = Symbol(“id”);
let user = {
[id]: 123
};
let clone = Object.assign({}, user);
alert( clone[id] ); // returns
123
Symbols are always different values, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry:__________ returns (creates if needed) a global symbol with key as the name
Symbol.for(key)