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:
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.
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.
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.
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.
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.
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 forString
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.