Chapter 2: The Javascript Console

2.3 Escape Sequences

Finally, let’s look at escape sequences. Escape sequences are used to display special “unprintable” characters such as a tab or a newline.

To display these characters, we need to use the \ (backslash) character to escape characters that otherwise have a different meaning.

For instance, to print a tab, we type the backslash character before the letter t, like this: \t. Without the \ character, the letter t will be printed. With it, a tab is printed. Hence, if you add

console.log('Hello\tWorld');

to chap2.js, you’ll get

Hello    World

as the output.

Other common uses of the backslash character are shown below:

To print a new line (\n)

Example:

console.log("Hello\nWorld");

Output:

Hello
World

To print the backslash character itself (\\)

Example:

console.log("\\");

Output:

\

To print a double quote, so that the double quote does not signal the end of the string (\")

**Under normal circumstances, double quotes are used to signal the start and end of a string. You'll learn about strings in the next chapter.

Example:

console.log("I am 5'9\" tall");

Output:

I am 5'9" tall

To print a single quote, so that the single quote does not signal the end of the string (\')

**Like double quotes, single quotes are also used to signal the start and end of a string unless they are preceded by the \ character. 

Example:

console.log('I am 5\'9" tall');

Output:

I am 5'9" tall