Essential JavaScript

Escaping Characters

There are certain characters that we can't simply type in a string. For example, a line break (when you press the Enter key and start a new line). Line breaks are a character themselves, but we can't just press Enter in the middle of a single-quote or double-quote string.

See what happens if we try to include a line break inside a string:

"This line break
will cause an error"

We need to add the line break another way.

Backticks

Strings created with backticks can include line breaks. Backticks create a special kind of string. Remember how we can only do interpolation when we are using backticks?

Try this:

`This line break
will be included in the string.`

The Backslash

Did you notice the output of the last example? It was a little strange:

"This line break\nwill be included in the string."

Instead of a line break, we see \n in the string. This is an escaped character.

We can include line breaks and other special characters by escaping them with a backslash. JavaScript will recognize that the backslash and the next character create a single character together.

Common Escape Codes

Below are some examples of common characters and how to escape them:

Character Escape Sequence
Line break (new line) \n
Tab (indentation) \t
Single quote \'
Double quote \"
Backslash \\

The backslash itself needs to be escaped. When JavaScript sees a backslash, it looks at the next character to see what is being escaped. If we just want a plain backslash, we put two backslashes so JavaScript knows we are not trying to escape something else.


Learning Goals

Code Editor