In JavaScript, you can convert a Symbol
to a string using the toString()
method. This method returns a string representation of the symbol.
Symbol().toString();
Note: the string representation of a symbol includes the string "Symbol"
followed by the symbol’s description in parentheses.
JavaScript Symbol to string example
Simple example code,
<!DOCTYPE html>
<html>
<body>
<script>
const mySymbol = Symbol('mySymbol');
const res = mySymbol.toString();
console.log(res);
console.log(typeof(res))
</script>
</body>
</html>
Output:
Symbol type conversions
1. String Conversion: You can convert a symbol to a string using the toString()
method or the String()
constructor.
const mySymbol = Symbol('mySymbol');
const res = mySymbol.toString();
const res = String(mySymbol);
2. Boolean Conversion: use the Boolean()
constructor but this will always return true
, since symbols are always truthy values in JavaScript.
const mySymbol = Symbol('mySymbol');
const res = Boolean(mySymbol);
console.log(res); // true
3. Number Conversion: You can define a custom valueOf()
method on a symbol object to return a numerical value. Better to use symbols as unique identifiers rather than numerical values.
const mySymbol = Symbol('mySymbol');
mySymbol.valueOf = function() {
return 42;
};
const res = Number(mySymbol);
console.log(res); // 42
4. Object Conversion: You can convert a symbol to an object using the Object()
constructor or the object literal syntax. This will create a new object with a property that has the symbol as its key.
const mySymbol = Symbol('mySymbol');
const res = Object(mySymbol);
console.log(typeof res); // "object"
console.log(res[mySymbol]); // undefined
const myObj = {[mySymbol]: 'hello'};
console.log(myObj[mySymbol]); // "hello"
Do comment if you have any doubts or suggestions on this JS conversion topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version