JavaScript string.concat() method
The concat()
method in JavaScript is used to join two or more strings together and return a new string. This method does not change the existing strings; instead, it creates a new string that combines the specified strings.
Syntax:
string
: The original string to which the other strings are appended.string1, string2, ..., stringN
: The strings to be concatenated. You can pass any number of string arguments to this method.
Return Value:
- It returns a new string that is the combination of the original string and the provided strings.
Example 1: Basic Usage
In this example, concat()
is used to combine "Hello"
, ", "
, "World"
, and "!"
into a single string.
Example 2: Concatenating Multiple Strings
You can concatenate multiple strings in one call:
Example 3: Handling Non-String Values
If you pass non-string values to concat()
, JavaScript will convert them to strings before concatenating:
Example 4: Using with Arrays
You can use concat()
with the spread operator to join an array of strings:
Important Note:
While concat()
is a valid way to join strings, it's worth mentioning that string concatenation using the +
operator is often more common and readable:
The +
operator is generally preferred for its simplicity and readability.
Performance Consideration:
Using concat()
is generally fine for small numbers of strings. However, when concatenating many strings (like in loops), using an array and the join()
method is often more efficient:
Summary:
- The
concat()
method is used to join two or more strings and returns a new string. - It does not modify the original strings.
- You can pass multiple string arguments, and non-string values will be converted to strings.
- While useful, string concatenation with the
+
operator is more common in practice. For concatenating many strings, consider using arrays and thejoin()
method for better performance.