Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Alexander Mills Avatar asked Sep 28 '17 22:09

Alexander Mills


People also ask

How do you check if a character is a symbol JavaScript?

To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned. Copied!

What is '$' in JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

How do you check if there is a letter in a string JavaScript?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.


2 Answers

Check it with typeof:

typeof x === 'symbol'
like image 168
jordiburgos Avatar answered Sep 24 '22 03:09

jordiburgos


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!

like image 45
daemonexmachina Avatar answered Sep 26 '22 03:09

daemonexmachina