How to convert an object to string using JavaScript?

Below are the methods to convert different objects to string.
Method 1: Using the function String()
The String() function converts the value of an object to a string.
Syntax:

String(object)

Parameter:

  • JavaScript Object

Example :



filter_none

edit
close

play_arrow

link
brightness_4
code

<script> 
var bool_to_s1 = Boolean(0);
var bool_to_s2 = Boolean(1);
var num_to_s = 1234;
    
document.write( typeof( bool_to_s1)+"<br>");
  
document.write( typeof(String( bool_to_s1))+ "<br>");
  
document.write( typeof( bool_to_s2)+ "<br>"); 
  
document.write(typeof(String( bool_to_s2))+ "<br>"); 
  
document.write( typeof( num_to_s)+ "<br>"); 
  
document.write(typeof(String( num_to_s))+ "<br>"); 
</script>                    

chevron_right


Output:

boolean
string
boolean
string
number
string

Method 2:Using JSON.stringify()
JSON.stringify() converts the javascript object to string which is needed to send data over web server.

Syntax:

 JSON.stringify(obj)

Parameter:

  • Can be object, array

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
var obj_to_str = 
{ name: "GeeksForGeeks", city: "Noida", contact:2488 };
var myJSON = JSON.stringify(obj_to_str);
document.write(myJSON)
</script>

chevron_right


Output:

{"name":"GeeksForGeeks", "city":"Noida", "contact":2488}

More about JSON.stringify()



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.