There are two ways to convert a value into a string.
The first is to use the toString()
method and the other way is to use String()
method.
This method's job is to return the string equivalent of the value.
let age = 1; let ageAsString = age.toString(); // the string "1" let found = true; let foundAsString = found.toString(); // the string "true"
The toString()
method is available on values that are numbers, Booleans, objects, and strings.
Each Javascript String has a toString()
method that returns a copy of itself.
If a value is null or undefined, toString()
method is not available.
In most cases, toString()
doesn't have any arguments.
When used on a number value, toString()
can accept a single argument: the radix.
By default, toString()
returns a string that represents the number as a decimal.
By passing in a radix, toString()
can output the value in binary, octal, hexadecimal, or any other valid base:
let num = 10; console.log(num.toString()); // "10" console.log(num.toString(2)); // "1010" console.log(num.toString(8)); // "12" console.log(num.toString(10)); // "10" console.log(num.toString(16)); // "a"
This example shows how the output of toString()
can change for numbers when providing a radix.
The value 10 can be output into any number of numeric formats.
The default with no argument is the same as providing a radix of 10.