JavaScript Escape Characters

When working with strings, you'll notice there are some characters that always seem to break your program. These include apostrophes, ampersands, double quotes etc.

When working with these characters, you need to use what is known as an escape character. An escape character enables you to output characters you wouldn't normally be able to, usually because the browser will interpret it differently to what you intended.

In JavaScript, the backslash (\) is an escape character.

As an example, let's say I want to display the following text: They call it an "escape" character.

Let's try that without an escape character:

Without an escape character:

The above code won't work as intended because, as soon as the browser encounters the first double quote, it will think that the string has finished. Further, it will result in an error because it will be expecting the closing bracket.

Code with an escape character:

The above code will display the double quotes as intended.

This is because, as soon as the browser encounters the backslash, it knows not to try to interpret the next character.