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.concat(string1, string2, ..., stringN)
  • 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

let greeting = "Hello"; let name = "World"; let message = greeting.concat(", ", name, "!"); console.log(message); // "Hello, World!"

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:

let part1 = "The quick"; let part2 = " brown fox"; let part3 = " jumps over"; let part4 = " the lazy dog"; let fullSentence = part1.concat(part2, part3, part4); console.log(fullSentence); // "The quick brown fox jumps over the lazy dog"

Example 3: Handling Non-String Values

If you pass non-string values to concat(), JavaScript will convert them to strings before concatenating:

let str = "The answer is: "; let number = 42; let result = str.concat(number); // "The answer is: 42" console.log(result);

Example 4: Using with Arrays

You can use concat() with the spread operator to join an array of strings:

let stringsArray = ["I ", "am ", "learning ", "JavaScript."]; let combinedString = "".concat(...stringsArray); console.log(combinedString); // "I am learning JavaScript."

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:

let message = greeting + ", " + name + "!"; console.log(message); // "Hello, World!"

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:

let strings = ["This ", "is ", "a ", "test."]; let combined = strings.join(""); // "This is a test." console.log(combined);

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 the join() method for better performance.