Search code examples
javascriptsymbols

Is it possible to access the value of a Symbol in JavaScript?


I have been just introduced to the concept of Symbols in JavaScript. I have been informed that they can be used to create unique identifiers to avoid potential clashes.

For example...

let user = {
    name        : "John",
    Symbol("id"): 123,    // Symbol("id") is a unique identifier
    Symbol("id"): 123     // and the Symbol("id") here is also different and unique
 };

... I understand the above code. However, what is the actual identifier value of each "Symbol("id")"? How do I find out?

Any pointers appreciated.


Solution

  • No, you cannot see the "raw" value of the symbol in the JS environment, because it is implemented using the native C ++ code of the JS engine itself, and this implementation does not provide an opportunity to display it anywhere in the console or on a page.

    You can think of symbols as big numbers and every time you create a symbol, a new random number gets generated (uuid). You can use that symbol (the random big number) as a key in objects. Regarding this definition, you can look at a possible implementation of the symbol in ES5:

    var Symbol;
    if (!Symbol) {
    Symbol = (function(Object){
    
    // (C) WebReflection Mit Style License
    
    var ObjectPrototype = Object.prototype,
        defineProperty = Object.defineProperty,
        prefix = '__simbol' + Math.random() + '__',
        id = 0;
    
    //... some other code
    

    You can see that Math.random() is used here, so Symbol there will have long big number as a his main property (unique with high possibility).

    Another way to explain what a symbol is is that a Symbol is just a piece of memory in which you can store some data. Each symbol will point to a different memory location. In the context of this definition, you can see the source code in C++ of the JS engine itself, for example V8 that is used in Chromium. If you know C++, you can try to find an implementation of Symbol() constructor there, but it won't be easy.

    Therefore, we can say that a Symbol is a kind of unique memory area that a certain string describes. The memory area itself it's already term from a low-level programming, so you can think of it as something like 1010010011...