How to Concatenate Strings using concat() in JavaScript?

Last updated on November 16, 2022

In this article, we explain how to use the concat() method, with syntax examples. The concat() function accepts the list of strings and returns the combined string in the result. Every programming language has a different syntax for concatenation operations.

The JavaScript concat() function is like you have many items in your hands that are quite difficult to carry. So you need a basket to put them all into it which is easy to handle.

The concat() function converts the non-string values to a string before concatenation.

let greeting = 'Hi';
let message = greeting.concat(' ', 'John');

console.log(message);
// Output: Hi John

In this above example you will get the out “Hi John”. You can also concatenate the array of strings.

let colors = ['Red', ' ','Green', ' ', 'Blue'];
let result = ''.concat(...colors);
console.log(result);
// Output: Red Green Blue

In the above example, you are looking […] at three dots which is a spread operator. The spread operator enables you to copy the array or object into another array or object.

Next, let’s concatenate integer values using the concat() function.

let num = [1,2,3];
let result = ''.concat(...num);
console.log(result);
// Output: 123

In this example, the concat() function converts numbers into string before concatenating them. It returns 123, as strings can’t calculate the numbers.

If you don’t want to use concat() function, then you will need to use plus symbol ( + )  between two strings for concatenating them.

let str = 'Hi' + ' ' + 'Coding World!';
console.log(str);
// Output: Hi Coding World!

In the above example plus symbol works the same as the concat() method, and in the result, you are getting a combined string.

Conclusion

JavaScript concat() function accepts the list of strings and returns them into a combined string. There are some other ways as well you can concatenate the string like join(), and plus “+” sign.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts