String Concatenation and Plus Operator

Concatenating strings is a fairly simple affair.

console.log("hello" + " world");
// hello world

This works because Javascript figures out the types, thinks that adding strings is not an intelligent thing to do, and therefore, concatenates the two strings.

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 -

  1. one + two = 3
  2. 3 + oneAgain = 31

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 -

  1. Force a string addition by deliberately including an empty string at the beginning.
console.log("" + one + two + oneAgain);
// 121
  1. 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.

comments powered by Disqus