DEV Community

Abhirup Datta
Abhirup Datta

Posted on

Javascript Symbol

A symbol is a primitive data type in Javascript, introduced in ES6.
A symbol is created using the Symbol constructor.The string is optional.

let sym1 = Symbol('xyz');
Enter fullscreen mode Exit fullscreen mode

One important behaviour of symbol it return a unique value.
So, the below code will log false

let sym1 = Symbol('foo');
let sym2 = Symbol('foo');

sym1 === sym2;  // false
typeof sym1;    // symbol
Enter fullscreen mode Exit fullscreen mode

Note: using the new operator will throw a TypeError. This is called incomplete constructor.

let sym = new Symbol('foo');
Enter fullscreen mode Exit fullscreen mode

Uncaught TypeError: Symbol is not a constructor


When symbol-ed keys are used in object, using for...in will ignore those keys. Even they would be ignored by Object.keys, but Object.getOwnPropertySymbols function can be used to get these.

let obj = {};

obj[Symbol('foo')] = 'a'
obj[Symbol.for('bar')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

for(let i in obj){
   console.log(i);   // logs c,d
}

Object.keys(obj);     // ['c', 'd']
Object.getOwnPropertySymbols(obj);  // [Symbol(foo), Symbol(bar)]
Enter fullscreen mode Exit fullscreen mode

Symbol.for and Symbol.keyFor

Symbol.for(string) is a function that checks for a symbol in the Global Symbol Registry(GSR) and returns it. If not present, it creates and returns it.

Symbol.keyFor(symbol) function is used to retrieve the identifier of the symbol, created using Symbol.for.

const foo1 = Symbol.for('foo');  // this one is created
const foo2 = Symbol.for('foo');  // retrieve the already created one
const bar = Symbol.for('bar');   // this one is created


foo1 === foo2;    // true
foo1 === bar;     // false
Symbol.keyFor(foo1)  // "foo"

const empty = Symbol.for();
console.log(Symbol.keyFor(empty));  // "undefined" (string)
Enter fullscreen mode Exit fullscreen mode

Note that, since Symbol.keyFor retrieves symbol from GSR, symbol created by the Symbol constructor is not accessible by keyFor and hence return undefined.

const Jam = Symbol('jam');
console.log(Symbol.keyFor(Jam));   // undefined
Enter fullscreen mode Exit fullscreen mode

Usage in React

Symbol can be used in trigger change detection, generally used in useEffect.

const [key, setKey] = useState(Symbol());

const changeKey = ()=>{
  setKey(Symbol());   // new value is set
}

useEffect(()=>{
  // anything to run on change of "key"
},[key]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)