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 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.