Tuesday, September 22, 2020

Symbols can be described as the part of metaprogramming tool introduced by es6,

Symbols are basically a new primitive type like numbers strings or Boolean, the main thing that this mechanism provides is a set of low level hooks into code mechanics and ability to create unique identifiers.

The interesting think is that you don see the identifier itself you only have the symbol, so you don’t have a key for example 1234, you only have the symbol and you know that I will represent a unique identifier.

This is useful that with symbols you can add properties to objects, the symbol will be the key in that object of which you know that are definitely unique.

Symbols have a Symbol function which can be used to create them.

Symbols are not iterable, that means if you loop over an object with a for loop, you won’t see the symbols as keys, of course there is a method to access it still but it’s not output in such a loop.

let symbol = Symbol('debug-flag');

console.log(symbol); // [object Symbol] { ... }

There is an object Symbol but we don’t see anything else

console.log(symbol.toString()); // "Symbol(debug-flag)"

This is how we create a Symbol.

Checking the Type:

console.log(typeof symbol);  "symbol"

As you can see it is a new primitive.

Comparing Symbols

let symbol2 = Symbol('debug-flag');

console.log(symbol == symbol2); //false

these symbols do not match because behind the scenes they stand for unique a different IDs.

Symbols are not printed out. Or in for loops.

let myObj = {
  name: 'carlos',
  [symbol]: 'calderon'
}

console.log(myObj); // [object Object] {name: "carlos"}

Symbols can be accessed explicitly:

console.log(myObj[symbol]); // "calderon"

You might have the case where you want two or more symbols that actually share the same ID.

let sharedSymbol = Symbol.for('product');
let sharedSymbol2 = Symbol.for('product');

console.log(sharedSymbol == sharedSymbol2); //true

How would this be usefull?

let sharedSymbol = Symbol.for('product');
let sharedSymbol2 = Symbol.for('product');

console.log(sharedSymbol == sharedSymbol2); //true

let myObj2 = {
  name: 'carlos',
}

function makeProduct(myObj2) {
  let productSymbol = Symbol.for('product')
  myObj2[productSymbol] = 'printer';
}

makeProduct(myObj2);
console.log(myObj2[sharedSymbol]); // "printer"

Event though the product symbol is not accessible outside of the function

makeProduct it refers to the same key as sharedSymbol and sharedSymbol2 and therefore I am able to use sharedSymbol and sharedSymbol2 to access this product.

[vc_custom_heading text=”Well Known Symbols “]

There are well known symbols already implemented in es6 and offers some core functionality which are well documented in Mozilla Developer Network documentation.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Well-known_symbols