Concatenating strings is a fairly simple affair.
console.log("hello" + " world"); // hello world
However, it may lead to problems.
const one = 1; const two = 2; const oneAgain = "1"; console.log(one + two + oneAgain); // 31
The addition takes place in two parts -
The addition across types work, albeit different from what a beginner expects and can be confusing.
Avoid the said behaviour by using either of the two approaches -
- Force a string addition by deliberately including an empty string at the beginning.
console.log("" + one + two + oneAgain); // 121
- Use a concat operator.
console.log("".concat(one, two, oneAgain)); // 121
I prefer the second option since the syntax makes is pretty explicit on what to expect.