menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:concat() method

menu

The concat() method in JavaScript is used to concatenate (combine) two or more strings and return a new string. It doesn't modify the original strings; instead, it creates and returns a new string that contains the concatenated values.

This method is particularly useful when you need to join strings together. Let's take a deep dive into the concat() function.

Basic Syntax:

The concat() method has the following syntax:

javascriptstring.concat(string1, string2, ..., stringN)
  • string: The original string that you want to concatenate other strings with.

  • string1, string2, ..., stringN: One or more strings you want to concatenate with the original string.

Example:

javascriptconst str1 = 'Hello, ';
const str2 = 'World!';
const result = str1.concat(str2);
console.log(result); // "Hello, World!"

Concatenating Multiple Strings:

You can concatenate multiple strings together in one concat() call:

javascriptconst str1 = 'Hello, ';
const str2 = 'beautiful ';
const str3 = 'World!';
const result = str1.concat(str2, str3);
console.log(result); // "Hello, beautiful World!"

Handling Non-String Values:

The concat() method can concatenate not only strings but also non-string values. It will implicitly convert non-string values to strings before concatenating:

javascriptconst str1 = 'Hello, ';
const num = 42;
const str2 = 'World!';
const result = str1.concat(num, str2);
console.log(result); // "Hello, 42World!"

Using Concatenation in Template Literals:

The concat() method can be useful when you want to concatenate strings within template literals:

javascriptconst name = 'John';
const greeting = `Hello, ${name.concat('!')}`;
console.log(greeting); // "Hello, John!"

Chainable:

You can chain multiple concat() calls together for more complex concatenation:

javascriptconst str1 = 'Hello, ';
const str2 = 'beautiful ';
const str3 = 'World!';
const exclamation = '!';
const result = str1.concat(str2).concat(str3, exclamation);
console.log(result); // "Hello, beautiful World!"

Avoiding concat() in Favor of + Operator:

While concat() is useful, JavaScript also supports the + operator for string concatenation, which is more concise and often preferred:

javascriptconst str1 = 'Hello, ';
const str2 = 'World!';
const result = str1 + str2;
console.log(result); // "Hello, World!"

In practice, developers tend to use the + operator more frequently due to its brevity.

The concat() method is useful when you need to concatenate strings in a more explicit way, especially when you have multiple strings to join. However, for simple string concatenation, the + operator is often the more concise and commonly used choice.

1280 x 720 px