JavaScript toString() method


The toString() method in JavaScript is used to convert an object to a string representation. This method is available on all objects in JavaScript, as it is inherited from the Object prototype. The toString() method is particularly useful for displaying objects in a readable format, debugging, and concatenating objects with strings.

Syntax:

object.toString()

Return Value:

  • Returns a string representation of the object. The exact output depends on the type of object.

Example 1: Basic Usage

For standard objects, calling toString() returns a string indicating the object type.

let obj = { name: "Alice", age: 25 }; let str = obj.toString(); console.log(str); // "[object Object]"

In this case, the toString() method returns the default string representation for an object: "[object Object]".

Example 2: Using with Arrays

When used on an array, toString() joins the array elements into a single string, separated by commas.

let arr = [1, 2, 3, 4, 5]; let str = arr.toString(); console.log(str); // "1,2,3,4,5"

Here, calling toString() on the array converts it to a string of its elements.

Example 3: Using with Numbers

For Number objects, toString() returns the numeric value as a string.

let numObj = new Number(42); let str = numObj.toString(); console.log(str); // "42" (as a string)

In this example, calling toString() on a Number object converts the number to its string representation.

Example 4: Using with Strings

For String objects, calling toString() returns the string itself.

let strObj = new String("Hello, World!"); let str = strObj.toString(); console.log(str); // "Hello, World!" (same as the original string)

In this case, the toString() method returns the string content without any modification.

Example 5: Custom Objects

You can override the toString() method in custom objects to provide a meaningful string representation.

let myObject = { name: "Alice", age: 25, toString: function() { return `${this.name} is ${this.age} years old.`; } }; console.log(myObject.toString()); // "Alice is 25 years old."

In this example, the custom toString() method formats the output to provide more context about the object.

Summary:

  • The toString() method converts an object to its string representation.
  • The output varies depending on the object type: it returns "[object Object]" for standard objects, joins array elements for arrays, and returns the string itself for String objects.
  • You can override toString() in custom objects to define how they should be represented as strings, which is useful for debugging and displaying information about the object.