A string is a piece of text. It's called a "string" because it's a string of characters, one after another, like beads on a necklace. Letters, digits, spaces, punctuation, emoji: they're all characters.
You create a string by wrapping text in quotes. JavaScript gives you three kinds:
const single = 'Hello there';
const double = "Hello there";
const backtick = `Hello there`;
console.log(single);
console.log(double);
console.log(backtick);
It prints
Hello there Hello there Hello there
Single quotes and double quotes work exactly the same. Pick one style and stick with it. (In this book, we mostly use double quotes.) Backticks are special and get their own lesson in a moment.
The only rule: the quote you start with must be the quote you end with.
const oops = "Hello there';
Quotes inside quotes
What if your text contains a quote mark? Like the word it's?
const message = 'It's a lovely day';
JavaScript reads 'It', thinks the string is over, and then gets very confused by the s a lovely day' that follows. Easy fix: use a different kind of quote on the outside:
const message = "It's a lovely day";
const speech = 'She said "wow" and fainted';
console.log(message);
console.log(speech);
It prints
It's a lovely day She said "wow" and fainted
Escape characters
Another option is to escape the quote by putting a backslash \ in front of it. The backslash tells JavaScript "the next character is part of the text, not the end of the string."
Backslashes can also create special characters that you can't easily type:
| Escape | What it makes |
|---|---|
\' | A single quote |
\" | A double quote |
\n | A new line |
\t | A tab (a big space) |
\\ | An actual backslash |
console.log('It\'s escaping time!');
console.log("Line one\nLine two\nLine three");
console.log("Name:\tOmar");
console.log("A backslash looks like this: \\");
It prints
It's escaping time! Line one Line two Line three Name: Omar A backslash looks like this: \
The empty string
A string can also contain nothing at all: "". This is called the empty string. It's still a string, it's just a string with zero characters, like an empty necklace chain. You'll find it surprisingly useful, for example as a starting point when you're building up a string piece by piece.