Joining Text with +
Introduction
Welcome back to Storing and Calculating with JavaScript Values! In the previous lesson we used + to add numbers together. In this lesson we discover that the very same + has a second job - and it is one we will use constantly.
So far, whenever we wanted a message to include a stored value, we put a comma between the pieces inside console.log, and JavaScript slotted a space between them. That is quick, but it gives us no say over the spacing: we cannot put a name in the middle of a sentence and then follow it immediately with an exclamation mark. To build sentences of our own, we need to join text together ourselves.
In this lesson, we will learn how to:
- Join two pieces of text into one with
+. - Join fixed text to a stored value to build a sentence.
- Put the spaces and punctuation exactly where we want them.
- Tell apart the two kinds of value we have met so far, text and numbers.
By the end, we will have a program that greets a customer by name and describes their order in a full, properly spaced sentence.
Two Kinds of Value
Before we start joining, let's name what we are joining. Every value we have stored or printed so far has been one of two kinds:
- Text: characters wrapped in quotation marks, such as
"Alex"or"Corner Cafe". The quotation marks are not part of the value; they only mark where it starts and ends. - Numbers: written plainly, such as
3or4.5, with no quotation marks.
Which kind a value is decides what JavaScript will do with it. Last lesson, + sat between two numbers and added them. In this lesson, + sits between two pieces of text, and it does something different.
Joining Two Pieces of Text
When both sides of a + are text, JavaScript does not add - it joins the two pieces into one longer piece of text, end to end:
The two pieces are glued together exactly as written, and the result is one value:
Notice what did not happen: JavaScript did not put a space between them. When we joined with commas inside console.log, the space came free. With +, nothing is added that we did not write. If we want a space, the space has to be part of one of the pieces:
The middle piece is text containing a single space, and now the two words are separated:
The space does not have to be a piece of its own. There are three common ways to write it, and all three are used in practice:
The first puts a trailing space at the end of the left piece, the second keeps the space as a dedicated piece of its own, and the third puts a leading space at the start of the right piece. JavaScript joins whatever characters it is given, so all three print the same line:
Programmers call this joining concatenation; "joining" says it just as well, and it is the word we will use.
