JavaScript object toString() method

Definition and usage

toString() The method returns the object as a string.

If toString() The method cannot return a string, then it returns "[object Object]".

Object.toString() Always returns the object constructor.

toString() The method does not change the original object.

Description

Every JavaScript object has toString() Method.

When you need to display an object as text (such as in HTML) or use an object as a string, JavaScript uses it internally toString() Method.

通常,您不会在自己的代码中使用它。

Instance

Example 1

Using toString() on an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.toString();

Try it yourself

Example 2

Using toString() on an object:

const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 19,
  eyeColor: "blue"
};
const keys = person.toString();

Try it yourself

Example 3

Using Object.toString() on an object:

const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 19,
  eyeColor: "blue"
};
const keys = Object.toString(person);

Try it yourself

Syntax

object.toString()

Parameter

No parameters.

Return value

Type Description
String Represents the string of an object.
"[object type]" If it fails to return a string.

Browser support

toString() It is an ECMAScript1 (ES1) feature.

All modern browsers support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support

Related Pages

JavaScript Object

JavaScript Object Definition

JavaScript Object Method

JavaScript Object Property