Computer >> Computer tutorials >  >> Programming >> Javascript

How to convert a value to a string in JavaScript?


There are 5 ways to convert a value to a string. They are 

  • Concatenating empty strings

  • Template strings 

  • JSON. stringify 

  • toString()

  • String()

Example

In the following example, all the above-mentioned methods were used to convert a value to a string and the final result was displayed as shown in the output.

<html>
<body>
<script>
   const value = 123;
   document.write((value + '') +" "+typeof (value + ''));
   document.write("</br>");
   document.write((`${value}`) +" "+typeof (`${value}`));
   document.write("</br>");
   document.write((JSON.stringify(value)) +" "+typeof (JSON.stringify(value)));
   document.write("</br>");
   document.write((value.toString()) +" "+typeof (value.toString()));
   document.write("</br>");
   document.write((String(value)) +" "+typeof(String(value)));
</script>
</body>
</html>

Output

123 string
123 string
123 string
123 string
123 string