Strings
Joining strings
Joining strings with + and appending with +=.
Why it exists
Almost all the text a user sees is assembled from pieces: "Hi, Ann!", "3 items in your cart, $15 total", "Order #1042 delivered". The template is fixed and the data is plugged in. Joining strings is the simplest way to do it, and it's where working with text starts: building a string character by character, putting together a page address, composing an error message.
Where it's used
- Messages to the user:
"Hi, " + name + "!". - Building a string piece by piece in a loop:
result += char. - Addresses and paths:
"/users/" + id. - Error text:
"Error: " + error.message.
Syntax
string1 + string2
string += addition;Examples
"Hello, " + "world"; // → "Hello, world"
"Age: " + 30; // → "Age: 30"
let word = "";
word += "a";
word += "b";
word; // → "ab"const name = "Ann";
const count = 3;
"Hi, " + name + "! Items: " + count; // → "Hi, Ann! Items: 3"
`Hi, ${name}! Items: ${count}`; // → "Hi, Ann! Items: 3"1 + 2 + "3"; // → "33"
"1" + 2 + 3; // → "123"
"1" + (2 + 3); // → "15"let stars = "";
for (let i = 0; i < 3; i++) stars += "★";
stars; // → "★★★"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
If at least one operand of + is a string, the other is turned into a string too and they're joined. The expression is evaluated left to right, so 1 + 2 + "3" is "33" (first 1 + 2 = 3, then joining), while "1" + 2 + 3 is "123".
Strings are immutable: + and += don't change the existing string, they create a new one. word += "a" is word = word + "a": the variable starts pointing to a new string. That's why an accumulating variable is declared with let.
The modern alternative is template literals in backticks: `Hi, ${name}!`. They're handier when there are many pieces, and they let you write text over several lines.
Traps
How it differs from…
- Arithmetic operators
The same
+adds two numbers. The operands' types decide what happens.
When to pick something else
When more than one or two variables go into a string, template literals `…${x}…` read better. And to join array items with a separator there's arr.join(", ") — no manual joining and no stray comma at the end.