Symbols

A new primitive type in ES6. They provide a unique identifier, but you don't see the unique identifier but only the symbol. Also might be used in MetaProgramming.

let symbol = Symbol('debug'); //Can pass on argument, only used for information purposes
console.log(symbol);
console.log(symbol.toString()); -> 'debug'
console.log(typeof symbol); -> symbol

//Check for uniqueness
let anotherSymbol = Symbol('debug'); 
console.log(symbol == anotherSymbol); -> false 

let obj = {
    name: 'max',
    [symbol]: 22 //Use a variable property name - We are using symbol as the property name
}

console.log(obj); -> We only see name:'max', could be accessed with the forInLoop
console.log(obj[symbol]) -> 22 - So its kinda hidden

Shared Symbol

What if we want to share the same id for two symbol?

let symbol1 = Symbol.for('age'); 
let symbol2 = Symbol.for('age');
console.log(symbol1 == symbol2) -> true

let person = {
    name: 'Max'
};

function makeAge(person) {
    let ageSymbol = Symbol.for('age'); 
    person[ageSymbol] = 27; 
}

makeAge(person); 
console.log(person[symbol1]); -> 27 //We can use symbol 1 or 2 to access age

Well known S=symbols

class Person {

}
//Can access symbol though static utils 
Person.prototype[Symbol.toStringTag] = 'Person'; 
let person = new Person(): 
console.log(person); -> [object Person] {...}

results matching ""

    No results matching ""