concat() JavaScript String Method – How to Merge Strings
Whenever you use concat() on a string, the method does the following:
- It concatenates (merges) its calling string with its arguments.
- It creates a new string with the merged values.
Syntax of the concat()
Method
concat()
accepts one or more arguments. Here is the syntax:
The item
arguments are the values you wish to concatenate with the callingString
.
Examples
Below are examples of the concat()
method.
How to merge a string with another string
The snippet above used concat()
to concatenate (merge) string1
with string2
.
How to merge a string with three other strings
The snippet above used concat()
to concatenate four strings.
How to merge a string with JavaScript data types
How to merge a string with a number
The snippet above used concat()
to merge string1
with a number.
How to merge a string with three numbers
The snippet above used concat()
to merge string1
with three numbers.
concat()
vs. Addition Operator vs. Template Literal
The concat()
method, addition operator (+
), and template literal “
concatenate strings in very similar ways, but they are not equivalent.
For instance, consider this snippet:
The three lines of code above appear to do the same thing, but here’s the difference:
concat()
and the template literal coerced53
directly to a string.- The addition operator (
+
) first coerced53
to its primitive data type (Number in this case). concat()
and the template literal call thetoString()
method in priority.- The addition operator (
+
) calls thevalueOf()
method in priority.
Therefore, suppose you use the addition operator with objects whose valueOf()
throws an Error. In that case, the browser will throw a TypeError. See this MDN description for a typical example.