Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "symbol" primitive data type in JavaScript [duplicate]

The new primitive type comes with ES6 which is Symbol type.The short definition says :

A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol object is an implicit object wrapper for the symbol primitive data type.

I did some research but I cannot understand why we need this primitive type exactly?

Thank you for your answers.

like image 981
BCRK Avatar asked Apr 22 '16 14:04

BCRK


People also ask

Is JavaScript symbol primitive data type?

Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined. It was introduced in ECMAScript 2015, so just a few years ago. It's a very peculiar data type.

Is symbol a primitive type?

Symbols are new primitive type introduced in ES6. Symbols are completely unique identifiers. Just like their primitive counterparts (Number, String, Boolean), they can be created using the factory function Symbol() which returns a Symbol.


1 Answers

This primitive type is useful for so-called "private" and/or "unique" keys.

Using a symbol, you know no one else who doesn't share this instance (instead of the string) will not be able to set a specific property on a map.

Example without symbols:

var map = {};
setProp(map);
setProp2(map);

function setProp(map) {
  map.prop = "hey";
}
function setProp2(map) {
  map.prop = "hey, version 2";
}

In this case, the 2nd function call will override the value in the first one.

However, with symbols, instead of just using "the string prop", we use the instance itself:

var map = {};
var symbol1 = Symbol("prop");
var symbol2 = Symbol("prop"); // same name, different instance – so it's a different symbol!
map[symbol1] = 1;
map[symbol2] = 2; // doesn't override the previous symbol's value
console.log(map[symbol1] + map[symbol2]); // logs 3
like image 118
Ven Avatar answered Nov 10 '22 04:11

Ven