Symbol

6 0 0
                                        

Symbol - is a primitive type that gives unique identifier to every variable you assigned it to. You can give a description to that variable which will be useful to you when you do some debugging. When you use the Symbol, you need to enclose it in brackets to differentiate with string type.

syntax:

let name = Symbol("description");

let objectName = {

     [name]: "value"

}

Note: When creating an object, the allowed type used in creating a key in key-value pairs is either a string or a Symbol.

=================

let place = Symbol("currently staying");

let objectPerson1 = {

     name: "Bell Cranel",

     age: 20,

     [place]: "La Isla Bonita"

};

fun displayPersonInfo1(){

     for(elem in objectPerson1){

         document.writeln(objectPerson1[elem]);

     }

}

=================

HTML

displayPersonInfo1()

Result:

Bell Cranel 20


Note: The Symbol is not displayed in part of the result of the loop. But to access it, you have to know the name of the variable declared as a Symbol.

objectPerson1[place]


Global symbol registry - it stores the global symbols in here. 

Symbol.for(symbolName) - this function retrieves a symbol if it exist or create a new one if it doesn't. Instead of using the Symbol("description"), you use Symbol.for("description").

==================

let sym1 = Symbol("id1");

let sym2 = Symbol.for("id2");

function displayCheckingOfSymbols(){

    let checkSym1 = Symbol.for("id1");

    let checkSym2 = Symbol.for("id2");

    document.writeln('sym1 equals checkSym1: ${sym1 == checkSym1} ***');

    document.writeln('sym2 equals checkSym2: ${sym2 == checkSym2}');

}

===================

HTML

displayCheckingOfSymbol()

Result:

sym1 equals checkSym1: false *** sym2 equals checkSym2: true


Note:

1. Symbol.for("name") - this returns a global symbol by name.

2. Symbol.keyFor(varName) - this returns a name by global symbol.



Javascript ProgrammingWhere stories live. Discover now