JavaScript Reference ยท String
String.prototype.concat()
Reference for JavaScript String.prototype.concat(): join strings into a new string, how arguments are converted, and why + or template literals are usually better.
The concat() method joins the string it is called on with one or more other values and returns the result as a new string. The original string is never changed, because strings are immutable.
In practice most code uses the + operator or a template literal instead, which are shorter and just as fast. concat() still turns up in older code and in places where a method call reads better in a chain.
"Hello".concat(", ", "world"); // "Hello, world"
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
string.concat() string.concat(str1) string.concat(str1, str2, /* โฆ, */ strN)
| Name | Description |
|---|---|
str1, โฆ, strN |
Values to append, in order. Each one is converted to a string. |
Return value: a new string made of the original string followed by the converted arguments. With no arguments you get a copy of the same string.
Exceptions: a TypeError if an argument is a symbol, because symbols cannot be converted to strings implicitly.
Usage notes
- It never changes the string it is called on. Store the return value if you need it.
- Arguments are converted with string conversion.
nullbecomes"null",undefinedbecomes"undefined", arrays become their comma-joined form, and plain objects become"[object Object]". - It is not identical to
+. The+operator asks an object for its primitive value in a "default" mode, which prefersvalueOf();concat()converts straight to a string, which preferstoString(). The second example shows the difference. Most objects never notice it. - Template literals are usually clearer:
`${first} ${last}`shows the final shape of the text. - Building long strings in a loop:
+=is well optimized in modern engines. For very large amounts of text, collecting pieces in an array and callingjoin()is also a good option. - Do not confuse it with
Array.prototype.concat(). The array version merges arrays and flattens one level. SeeArray.prototype.concat(). - Generic: it can be called on other values with
String.prototype.concat.call(value, ...), butnullandundefinedas the receiver throw aTypeError.
Browser support
concat() works in every browser, old and new.