How to Convert an Object to String in JavaScript

To convert an Object to a String in JavaScript, you can use “JSON.stringify()”, “string interpolation”, and “concatenating object properties”.

Method 1: Using the JSON.stringify()

The JSON.stringify() method converts an object to a JSON-formatted string. It is helpful when you need to transmit data as JSON or store it in a human-readable format.

const obj = {
  name: "Krunal Lathiya",
  age: 30
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);

Output

{"name":"Krunal Lathiya","age":30}

Method 2: Using the string interpolation(template literals)

Template literals, enclosed by backticks, allow you to embed expressions within the string using the ${expression} syntax. This method is helpful for creating custom string representations of objects.

const obj = {
  name: "Krunal Lathiya",
  age: 30
};

const objString = `Name: ${obj.name}, Age: ${obj.age}`;
console.log(objString);

Output

Name: Krunal Lathiya, Age: 30

Method 3: Concatenating object properties

Another approach is to create a string representation by manually concatenating object properties. This method can be useful when you need a specific format for the string representation.

const obj = {
  name: "Krunal Lathiya",
  age: 30,
};

const objString = 'Name: ' + obj.name + ', Age: ' + obj.age;
console.log(objString);

Output

Name: Krunal Lathiya, Age: 30

Depending on your requirements, you can choose the most appropriate method to convert an object to a string in JavaScript.

Leave a Comment