This page looks best with JavaScript enabled

String Concatenation and Plus Operator

 ·   ·  ☕ 1 min read

Concatenating strings is a fairly simple affair.

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

1
2
3
4
5
6
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.
1
2
console.log("" + one + two + oneAgain);
// 121
  1. Use a concat operator.
1
2
console.log("".concat(one, two, oneAgain));
// 121

I prefer the second option since the syntax makes is pretty explicit on what to expect.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things