'Check if value is a Symbol in JavaScript

How can I check if a value is Symbol in JS?

I do not see a Symbol.isSymbol(x) method. My test of (x instanceof Symbol) does not seem to work either.



Solution 1:[1]

Check it with typeof:

typeof x === 'symbol'

Solution 2:[2]

Updated 2022: Go with the accepted answer! If you're working in an environment so outdated that Symbol needs to be polyfilled, then you'll know that already. You'll be excruciatingly aware of it. You'll be haunted by it. Then, sure, use my answer. Otherwise don't bother. typeof x === 'symbol' is almost definitely all you need these days.


In ES 2015 and up, typeof x === 'symbol' is all that's needed. But it won't work if you're transpiling your code to ES 5.1 or earlier, even if you're using a polyfill for the Symbol builtin.

Every polyfill I've seen, including the babel-polyfill, implements Symbol as an object (i.e. typeof x === 'object') using a constructor function called Symbol. So in those cases you can check that Object.prototype.toString.call (x) === '[object Symbol]'*.

Putting it all together, then, we get:

function isSymbol (x) {
    return typeof x === 'symbol'
        || typeof x === 'object' && Object.prototype.toString.call (x) === '[object Symbol]';
}

*Note that I'm not using instanceof in the transpiled scenario. The problem with instanceof is that it only returns true for objects that were created within the same global context as the assertion being made. So if, say, a web worker passes a symbol back to your page, or symbols are passed between iframes, then x instanceof Symbol will return false! This has always been true of all object types, including the builtins. instanceof often works just fine, but if there's any chance of your code being in a "multi-frame" scenario as I've described, use with caution!

Solution 3:[3]

The most efficient way is to test the constructor of a value:

const result = (value && value.constructor === Symbol);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jordiburgos
Solution 2
Solution 3 Danny Apostolov