How to convert a value to a string in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

<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
raja
Published on 30-Jul-2019 15:19:34
Advertisements