JavaScript Reference ยท Array
Array.prototype.toString()
Reference for JavaScript Array.prototype.toString(): how arrays turn into comma-separated strings, how nested arrays, null and undefined behave, and when it runs.
The toString() method returns a string that represents the array: its elements converted to strings and joined with commas. Internally it simply calls join() with the default separator.
You seldom call it directly, but it runs automatically whenever an array is used where a string is expected, such as in string concatenation or a template literal. That is why "Items: " + [1, 2, 3] gives "Items: 1,2,3".
[1, 2, 3].toString(); // "1,2,3"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.toString()
Parameters: none.
Return value: a string with the elements joined by commas (no spaces).
Exceptions: none for ordinary arrays. If an element's own conversion throws, such as a Symbol, that error propagates (TypeError: Cannot convert a Symbol value to a string).
Usage notes
- It is
join(","). Elements that arenullorundefined(and empty slots) become empty strings, so[1, null, 2]becomes"1,,2". An empty array gives"". - Nested arrays go through
toString()too, so the nesting disappears and you cannot tell[1, [2, 3]]from[1, 2, 3]in the output. - Implicit conversions use it. String concatenation, template literals,
String(array)and loose comparison (==) with a string or number all lead here. That is why[5] == 5istrue, a classic surprise. - Not a serialization format. The output is lossy and cannot be parsed back reliably. Use
JSON.stringify()for data, andjoin()when you want a different separator. - Objects inside show as
[object Object]unless they define their owntoString(). - Calling on a non-array. The method is generic: if the object has a callable
join, that is used; otherwise it falls back toObject.prototype.toString, producing something like"[object Object]". - Display tip. To show arrays to users, build the text yourself with
join()orIntl.ListFormat, so you control separators and wording.
Browser support
toString() is a classic method available in every browser and engine.