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:
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]"
, whereType
is the internal type of the object (e.g.,Object
,Array
,Function
, etc.).
Example 1: Default Usage
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.
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.
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.
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.