JavaScript gives you three ways to write a string, and they are not interchangeable. You have single quotes, double quotes, and backticks, and each one has its own rules about escaping, line breaks, and embedded expressions. Picking the wrong one is the cause of a surprising number of syntax errors in code that you have not written yet.
The previous lesson in this module covered "Numbers in JavaScript: Integers, Floats, BigInt", and the next lesson in this module is about "Booleans, null and Missing Values Explained".
Which quote styles does JavaScript have?
Three of them. 'single', "double", and `backtick`. The first two are interchangeable in almost every situation. The third is a different feature altogether, because a backtick string is called a template literal and it adds interpolation and multi-line support.
const single = 'It is working';
const double = "She said \"hello\"";
const withApostrophe = 'Ada\'s notebook';
const template = `Total: ${19.99 + 5} USD`;
console.log(single);
console.log(double);
console.log(withApostrophe);
console.log(template);
That prints four lines. They are It is working, She said "hello", Ada's notebook, and Total: 24.99 USD.
Notice the pattern in the second and the third line. When a string contains the quote character that you are using, you have two choices. You can escape it with a backslash, or you can switch to the other quote style. Switching is usually cleaner, because "Ada's notebook" needs no escapes at all and neither does 'She said "hello"'. Escaping is fine, but every backslash is one more thing to get wrong, so prefer the quote style that does not need one.
How do I put special characters inside a string?
A backslash followed by a character tells JavaScript to treat that character in a special way. Here are the ones that you will use most often.
const multi = "Line one\nLine two";
const tabbed = "Name\tAmount";
const path = "C:\\Users\\ada";
const unicode = "\u2713 done";
console.log(multi);
console.log(tabbed);
console.log(path);
console.log(unicode);
The first line breaks across two lines when it is printed, and the second one inserts a tab. The third one prints C:\Users\ada, and notice that a literal backslash in a Windows path has to be doubled. The fourth one prints a check mark, because \u2713 is its Unicode code point. The escapes \n, \t, \\, \', \", and \b cover most of what you need in practice.
One gotcha is worth knowing. An escape only works inside a quoted string. Writing \n outside of quotes is a syntax error, and so is a raw line break inside a single-quoted or double-quoted string. That is why a multi-line string needs either escapes or a template literal.
What makes template literals different?
A backtick string can span several lines, and it can contain ${ } expressions whose results are placed straight into the text. Nothing has to be concatenated.
const customer = { name: "Ada", tier: "gold" };
const items = 3;
const unitPrice = 249.5;
const summary = `Customer: ${customer.name} (${customer.tier})
Items: ${items}
Total: ${(unitPrice * items).toFixed(2)}`;
console.log(summary);
The output is three lines. They are Customer: Ada (gold), Items: 3, and Total: 748.50. Everything inside ${ } is a normal JavaScript expression, which means a property access, a variable, a function call, or an arithmetic calculation. It is not limited to a plain variable name, which is why the total needed a toFixed(2) call to become a string with two decimal places.
Why should I use a template literal for multi-line text?
Because the alternative is string concatenation with + and a trailing \n on every single line, which is easy to get wrong and unpleasant to edit later.
const joined = "First line\n" + "Second line";
const literal = `First line
Second line`;
console.log(joined === literal);
console.log(joined);
The comparison prints true, and that tells you the two approaches produce exactly the same string. The difference is in the source code. The template literal keeps the real line breaks, so there are no stray spaces and no missing escapes when you edit it later.
Template literals are worth reaching for whenever the text contains a value. If a string has nothing placed inside it, plain quotes are the more conventional choice, and many style guides insist on that for consistency.
Can you change a string after you create it?
No. Strings are primitive values and they are immutable. Every string method returns a new string instead of editing the original one.
const original = "Hello";
const changed = original.toUpperCase();
console.log(original); // "Hello"
console.log(changed); // "HELLO"
console.log(original === changed); // false
This is a small thing with a large consequence. Because a string cannot change, it is safe to pass around and to store, without worrying that some other piece of code will alter it underneath you. It is also why string-building loops are slow. Every round allocates a new string, and the garbage collector has to clean up the old one. For long loops, use an array and do a single join at the end.
How does .length count characters?
It counts UTF-16 code units, which is almost always the number of characters that you expect for plain text. It is occasionally not, because characters outside the basic multilingual plane take two code units each.
console.log("Hello".length); // 5
console.log("café".length); // 4, the e with the accent is one code unit
console.log("\u{1F44B}".length); // 2, a wave emoji is a surrogate pair
console.log([..."\u{1F44B}"].length); // 1, but one code point
The last two lines are the interesting pair. Spreading the emoji into an array counts code points, so you get 1, while .length reports 2. If you are counting the characters that a user sees in text that may contain emoji, use [...text].length instead of text.length.
Which quote should I use?
- Use single quotes for ordinary text, and match the style of the code around you.
- Switch to double quotes when the text contains an apostrophe, and back to single quotes when it contains double quotes. Escaping is the fallback and not the first choice.
- Use a backtick whenever you place a value inside the text or you need more than one line.
- Use
\n,\t, and\\for control characters and literal backslashes, and use\uXXXXfor a Unicode code point. - Strings are immutable, so every method returns a new string and nothing that you hold on to can change underneath you.
.lengthcounts UTF-16 code units, which is not the same as counting characters when emoji are involved.
Try it yourself: write a function that takes a first name, a last name, and a city, and that returns a greeting. Do it three times. Use string concatenation once, a template literal once, and a template literal that spans several lines once. Print all three and compare them with ===. Then break the concatenation version on purpose by forgetting one of the spaces, and see how much harder that mistake is to spot in the concatenated form than it is in the template literal.