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.