CodeBlanks Logo Icon CodeBlanks

Escape sequences

JavaScript course · Beginner · Lesson 34/133

Learn how to write special characters inside strings with \n, \t, \\ and \'.

Special characters: escape sequences

To write characters that have a special meaning inside a string you use escape sequences. They start with a backslash (\).

Common ones: \n (new line), \t (tab), \\ (a backslash itself), \' (single quote), \" (double quote).

For example "Line 1\nLine 2" gives a two line string. When you write a path you use "C:\\dev"; a single \ would be read as an escape.

Escaping the same quote

If a string starts with a single quote and you want a single quote inside, you must write the inner one as \'. Otherwise JavaScript closes the string there.

Example: 'Ayşe\'s book'. The same rule applies to double quotes inside double quotes: "He \"said\" that".

The easy path is to use a different quote on the outside. You only need an escape when you must use the same kind inside.

Exercise Join two lines with a new line

Declare firstLine as "Hello" and secondLine as "World". Build message as a template literal containing ${firstLine}, then the \n escape, then ${secondLine}. Log message with console.log.

Show example solution
const firstLine = "Hello";
const secondLine = "World";
const message = `${firstLine}\n${secondLine}`;
console.log(message);

Test yourself

  1. How does the string "a\nb" appear on screen?

    console.log("a\nb");
    • Two lines: a then b
    • One line: anb
    • It throws an error
    • Three lines: a, blank, b
    Show answer

    Two lines: a then b — Correct. \n is a new line character; it prints a, breaks the line, then prints b.

  2. Write the new line escape

    const line = "Satır 1____Satır 2";
    Show answer
    const line = "Satır 1\nSatır 2";
  3. Match each escape to its meaning

    \n
    New line
    \t
    Tab
    \\
    Backslash
    \'
    Single quote
  4. What does the string "C:\\dev" print?

    console.log("C:\\dev");
    • C:\\dev
    • C:dev
    • C:\dev
    • It throws an error
    Show answer

    C:\dev — Correct. When the source has \\ JavaScript reads it as a single \ and prints C:\dev.

All lessons in Beginner