How to convert an object to string using JavaScript ?

Given an object and the task is to convert the Object to a String using JavaScript. There are some methods to convert different objects to strings, these are:
Methods to Convert an Object to a String
- Using String() Constructor
- Using JSON.stringify() Method
- Using the plus (+) Operator with string:
Method 1: Using String() Constructor
This method converts the value of an object to a string.Â
Syntax:
String(object)
Example:Â In this example, we will use the string() method to convert the objects to a string.
javascript
// Inputslet bool_to_s1 = Boolean(0);let bool_to_s2 = Boolean(1);let num_to_s = 1234;Â
// Display type of first inputconsole.log( typeof(bool_to_s1));Â
// After converting to stringconsole.log( typeof(String(bool_to_s1)));Â
// Display type of first inputconsole.log( typeof(bool_to_s2));Â
// After converting to stringconsole.log(typeof(String(bool_to_s2)));Â
// Display type of first inputconsole.log( typeof(num_to_s));Â
// After converting to stringconsole.log(typeof(String(num_to_s))); |
boolean string boolean string number string
Method 2: Using JSON.stringify() Method
This method converts the JavaScript object to a string which is needed to send data over the web server.Â
Syntax:
JSON.stringify(obj)
Example:Â In this example, we will use JSON.stringify() method for conversion of an object to a string.
javascript
// Input objectlet obj_to_str = { Â Â Â Â name: "GeeksForGeeks", Â Â Â Â city: "Noida", Â Â Â Â contact: 2488 };Â
// Converion to stringlet myJSON = JSON.stringify(obj_to_str);Â
// Display outputconsole.log(myJSON); |
{"name":"GeeksForGeeks","city":"Noida","contact":2488}
Method 3: Using the plus (+) Operator with string
By default concatenation operation of a string with any data type value first, and convert the value to string type then concatenate it to string.Â
Syntax:
"" + object ;
Example: In this method, we will use + operate to change objects to strings.
Javascript
// Input objectslet obj1 = new Object();let obj2 = { ww : 99 , ss : 22};Â
// Display type of objects before// and after their conversionconsole.log( typeof( obj1 ));console.log( typeof( '' + obj1));console.log( typeof( obj2 ));console.log(typeof( '' + obj2 )); |
object string object string



