Students Empire

Learn Something New

Converting To String

There are two ways to convert a value into a string.

First, use the toString() method that every value has. toString() returns the string equivalent of the value. Consider this example:

				var age = 11; 
				var ageAsString = age.toString();    //the string "11" 
				var found = true; 
				var foundAsString = found.toString(); //the string "true"

The toString() method is available on numbers, Booleans, objects, and strings.

String has a toString() method that returns a copy of itself.

If a value is null or undefined, this method is not available.

When used on a number value, toString() accepts 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:

				var 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" 

If you're not sure that a value is null or undefined, use the String() casting function, which returns a string regardless of the value type.

The String() function follows these rules:

  • If the value has a toString() method, it is called (with no arguments) and the result is returned.
  • If the value is null, "null" is returned.
  • If the value is undefined, "undefined" is returned.
				var value1 = 1; 
				var value2 = true; 
				var value3 = null; 
				var value4; 
				console.log(String(value1));     //"1" 
				console.log(String(value2));     //"true" 
				console.log(String(value3));     //"null" 
				console.log(String(value4));     //"undefined" 

In the code above four values are converted into strings: a number, a Boolean, null, and undefined.

The result for the number and the Boolean are the same as if toString() were called.

Because toString() isn't available on "null" and "undefined", the String() method simply returns literal text for those values.