The basics of syntax

INPUT · Slides

Joining text together

01 / 06

You can join strings with + too

+ is not only for numbers. Put + between two strings and you get one string.

This is called concatenation.

console.log("apple" + "juice");

Result

applejuice

02 / 06

The same symbol, a different job

What + does depends on what is either side of it.

  • number + number … addition
  • string + string … joining

Same symbol, completely different result. You have to read it with that in mind.

console.log(3 + 5);console.log("3" + "5");

Result

8
35

03 / 06

If you want a space, put one in

Joining does not add a space for you. If you want one, write it into the string.

console.log("good" + "morning");console.log("good" + " " + "morning");

Result

goodmorning
good morning

04 / 06

What happens when you mix a string and a number

If either side is a string, the number is turned into a string first and then joined on.

So the result is a string. It is not an addition.

console.log("the price is " + 150);console.log(1 + "2");

Result

the price is 150
12

05 / 06

It works from the left

When several + sit in a row they are handled from the left, and that order can change the result.

Wrap the part you want done first in ( ).

console.log("total " + 1 + 2);console.log("total " + (1 + 2));

Result

total 12
total 3

06 / 06

Where people come unstuck

That + decides its job from what is either side of it is one of JavaScript's quirks, and a rich source of bugs.

When you meant to add numbers up and the digits ended up stuck together instead, something along the way turned into a string. Anything typed into a box on a page arrives as a string, so you will meet this again the moment you build something real.

For now, knowing that the same + does two different jobs is enough.