xxxxxxxxxx
// two symbols with the same description
const value1 = Symbol('hello');
const value2 = Symbol('hello');
console.log(value1 === value2); // false
xxxxxxxxxx
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')
console.log(Symbol(sym2==sym3)); /*false, symbols are guaranteed to be unique*/
xxxxxxxxxx
Symbol is a primitive data type of JS along with string,number,bool,null and undef
which are used to identify object properties since none is equal to the other.
xxxxxxxxxx
// get symbol by name
let sym = Symbol.for('hello');
let sym1 = Symbol.for('id');
// get name by symbol
console.log( Symbol.keyFor(sym) ); // hello
console.log( Symbol.keyFor(sym1) ); // id
xxxxxxxxxx
Symbols are primatives for unique values in javascript
> Symbol(value) returns a unique symbol
> Symbol.for(value) returns a unique symbol, but two calls using the
same key will return the same symbol, within the scope
They can be useful because they are hidden from most iteration functions.
For ex, if you want to add a value to an object that you got back from a
third-party api. This will make sure your value doesn't appear in iteration
functions, and also won't require changing how the api is set up
xxxxxxxxxx
for() Searches for existing symbols
keyFor() Returns a shared symbol key from the global symbol registry.
toSource() Returns a string containing the source of the Symbol object
toString() Returns a string containing the description of the Symbol
valueOf() Returns the primitive value of the Symbol object.
xxxxxxxxxx
// get symbol by name
let sym = Symbol.for('hello');
let sym1 = Symbol.for('id');
// get name by symbol
console.log( Symbol.keyFor(sym) ); // hello
console.log( Symbol.keyFor(sym1) ); // id
xxxxxxxxxx
const x = Symbol('hey');
// description property
console.log(x.description); // hey
const stringArray = ['a', 'b', 'c'];
const numberArray = [1, 2, 3];
// isConcatSpreadable property
numberArray[Symbol.isConcatSpreadable] = false;
let result = stringArray.concat(numberArray);
console.log(result); // ["a", "b", "c", [1, 2, 3]]
xxxxxxxxxx
let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')
xxxxxxxxxx
// two symbols with the same description
const value1 = Symbol('hello');
const value2 = Symbol('hello');
console.log(value1 === value2); // false