Escape Characters

In JavaScript, escape characters allow you to include special characters in strings that are otherwise difficult or impossible to type directly.

Illustration of escape_characters
Illustration of escape_characters

💡 What are Escape Characters?

Escape characters start with a backslash \\ followed by a character that has a special meaning, enabling insertion of characters like quotes, newlines, or tabs into strings.

Common use cases for escape characters include:

  • Including quotes inside strings without ending the string early
  • Adding new lines or tabs inside strings
  • Inserting Unicode or special symbols
Common Escape Characters
Escape SequenceResult
\\'Single quote: '
\\"Double quote: "
\\\\Backslash: \
\ New line (line break)
\\tTab space
\\rCarriage return
\\uXXXXUnicode character (hex code)

📌 Deep Dive: Using Quotes Inside Strings

JAVASCRIPT
const quote = 'It\'s a sunny day';
const dialog = "He said, \"Hello!\"";
Output
It's a sunny day
He said, "Hello!"

📌 Deep Dive: New Lines and Tabs

JAVASCRIPT
const multiline = "Line 1
Line 2
\tIndented line 3";
console.log(multiline);
Output
Line 1
Line 2
Indented line 3

⚠️ Keep in Mind

Without escape characters, including quotes or special whitespace in strings can cause syntax errors or unexpected output.

You can also insert Unicode characters using \\u followed by a 4-digit hexadecimal code. For example, \\u2764 inserts a heart symbol ❤.

📌 Deep Dive: Unicode Escape

JAVASCRIPT
const heart = "\u2764";
console.log(heart);
Output

💡 Summary

  • Use \\' or \\" to include quotes inside strings.
  • \ adds a new line, and \\t adds a tab.
  • Unicode escapes \\uXXXX allow special characters by hex code.
  • Escape sequences start with a backslash \\ followed by a character.