JavaScript escape characters Tutorial

There are some characters in computers that don’t have a written symbol which makes them non-printable.

For example:

  • White-space: Tab, backspace, newline, space.

  • Form feed

Also when creating a string, if we use a pair of double quotations, by default we can’t use another double quotation inside the string anymore. Likewise, if we use single quotation to create a string, we can’t use another single quotation inside the string anymore.

Note: The same is true if we used backticks to create a string.

This is related to the compiler. Basically the compiler cannot distinguish the beginning and ending symbols that we used for the target string.

Example:

//WRONG
var character = 'example of using 3 single quotation' marks in a wrong way';

When a compiler tries to compile this statement, it will get confuse about where the first and last quotation marks are! And so it will stop compiling and returns error instead.

But the JavaScript language brought an alternative to these characters which is called escape-sequence and they allow us to use these non-printable characters and add single and double quotation marks to the values of variables in a program.

The effect of using these escape-sequence is exactly the same as if we’re using those especial characters.

Sequence Meaning
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
\ Backslash ()
‘ Single quote (‘)
“ Double quote (“)

Example:


var character = 'example of using 3 single quotation' marks in the correct way';

Now because we used the escape-sequence of the single-quotation mark, the character variable can store the single-quotation mark and the compiler will not complain about this statement any more.

Another example:

<!DOCTYPE html>

<html>

<head>

<title>JS is fun :)</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<h3>Output:</h3>

<p id = "link"></p>

<script>

console.log(`tt John Doe`);

</script>

</body>

</html>

Output:

John Doe

In this example we’ve added two tab via t escape sequence to the message that we sent to the browser’s console.