How to Convert an Object to String in JavaScript

Here are three ways to convert an Object to a String in JavaScript:

  1. Using JSON.stringify()
  2. Using toString()
  3. Using String()

Method 1: Using the JSON.stringify()

The JSON.stringify() method converts an object to a JSON-formatted string. It is called “Stringification”. 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 toString()

The default toString() method for objects doesn’t visually represent its contents. It simply returns “[object Object]”. However, the behavior of toString() for other built-in objects, like numbers and arrays, is more informative.

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

console.log(person.toString());

Output

[object Object]

If you want a more descriptive string representation of the object’s contents for custom or complex objects, you must override the toString() method.

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  toString: function() {
    return `${this.firstName} ${this.lastName}, Age: ${this.age}`;
  }
};

console.log(person.toString());

Output

John Doe, Age: 30

Method 3: Using the String() Constructor

The String() constructor can be used to convert almost any value, including objects, to a string. Passing an object to the String() function internally calls that object’s toString() method.

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  toString: function() {
    return `${this.firstName} ${this.lastName}, Age: ${this.age}`;
  }
};

console.log(String(person));

Output

John Doe, Age: 30

As you can see, the behavior of the String() function is influenced by the toString() method of the object.

If the toString() method is overridden to provide a custom string representation, the String() function will return that custom representation. If not, it defaults to “[object Object]”.

Related posts

JavaScript String to Object

JavaScript String to Boolean

PHP Array to JavaScript Object

JavaScript Array to Object