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.
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!
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.
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.
Check it with typeof:
typeof x === 'symbol'
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With