Strings: Text in Quotes

Grade 2, page 2 of 13. A two-minute read.

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:

JavaScript
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.

JavaScriptHas a bug
const oops = "Hello there';

Quotes inside quotes

What if your text contains a quote mark? Like the word it's?

JavaScriptHas a bug
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:

JavaScript
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:

EscapeWhat it makes
\'A single quote
\"A double quote
\nA new line
\tA tab (a big space)
\\An actual backslash
JavaScript
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.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning