30 Days Of JavaScript

Day 14: Strings and JSON

Lesson 3: Concatenation

+

This a fancy name for joining strings together.

We can join multiple strings together with the + operator, like this:

JavaScript is doing a lot under the hood here to determine if it should treat + like adding two numbers together or if it should join them like strings.

The first thing it does is checks to see if it's been given numbers, if they have then they will numerically add them. If they aren't then they will be concatenated. So this will print 6.

1const first = 1;
2const second = 2;
3const third = 3;
4const name = first + second + third;
5console.log(name);

But this will print "33"

1const first = 1;
2const second = 2;
3const third = "3";
4const name = first + second + third;
5console.log(name);

Because 1 and 2 are added, which gives 3. Then third is concatenated on because it's a string, so we get a string output.

This sounds very confusing and has been the source of bugs in many a JavaScript developer's code however, after some time you get used to it. Evaluating left to right, if the operands (the inputs to +) are numbers then they are added, if one of them isn't then they are concatenated.

.concat()

You can also concatenate strings by calling the .concat() method on a string.

This isn't all that common but you should know about it.

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co