JavaScript Obj.toString() method


The obj.toString() method in JavaScript is a built-in function that returns a string representation of the specified object. It is inherited by all objects from Object.prototype, and its default implementation can be overridden by individual objects to provide a more specific string representation.

Syntax:

obj.toString();

Return Value:

  • The method returns a string representing the object. The exact output can depend on the type of object and any custom implementations of the toString method.

Default Behavior:

  • For most objects, the default toString() method returns a string of the form "[object Type]", where Type is the internal type of the object (e.g., Object, Array, Function, etc.).

Example 1: Default Usage

const obj = {}; console.log(obj.toString()); // Output: "[object Object]" const arr = []; console.log(arr.toString()); // Output: "" const num = 42; console.log(num.toString()); // Output: "42"

In this example, the toString() method returns a string indicating the type of the object for an empty object, while for an array, it returns an empty string since the array has no elements. For the number 42, it returns its string representation.

Example 2: Overriding toString()

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

const person = { name: 'Alice', age: 30, toString: function() { return `${this.name} is ${this.age} years old.`; } }; console.log(person.toString()); // Output: "Alice is 30 years old."

In this example, the person object has a custom toString() method that returns a more informative string representation.

Example 3: Using with Arrays

The toString() method for arrays joins the elements of the array into a single string, separated by commas.

const fruits = ['apple', 'banana', 'cherry']; console.log(fruits.toString()); // Output: "apple,banana,cherry"

In this case, calling toString() on the fruits array concatenates its elements into a comma-separated string.

Example 4: Using with Functions

When toString() is called on a function, it returns the source code of the function as a string.

function greet() { return 'Hello!'; } console.log(greet.toString()); // Output: "function greet() { return 'Hello!'; }"

Here, the output is the text representation of the greet function, including its body.

Summary:

  • obj.toString() is a method that returns a string representation of an object.
  • The default behavior provides a string indicating the object's type, but it can be overridden to provide custom representations.
  • The method behaves differently for different types of objects, such as arrays and functions, offering flexible string representations based on the context.