Strings are used to represent text-based data and are mostly defined using either single quotes (
') or double quotes (
let name1 = 'John Doe'; let name2 = "John Doe";
Due to the fact that these quotation marks are used to denote strings, you need to be careful when using apostrophes and quotes in strings.
let quote = "He said, "I learned from freeCodeCamp!"";
This will throw an error, as seen below:
Uncaught SyntaxError: Unexpected identifier 'I'
- By using the opposite string syntax
- Using an escape character
- Using template literals
" to escape a string. To do so, you must wrap the string in the opposite syntax of what you are escaping.
let quote = 'He said, "I learned from freeCodeCamp!"'; console.log(quote); // He said, "I learned from freeCodeCamp!" let apostrophe = "It's a beautiful day"; console.log(apostrophe); // It's a beautiful day
This means if you use double quotes to wrap your string, you can use an apostrophe within the string. Also if you wrap your string in single quotes, then you can use double quotes within the string.
But there are limitations to this because what if you have to use a quote and an apostrophe within the same string? Then you can use an escape character (
How to Use the Escape Character (
\ (backslash) character. The backslash indicates that the next character should be treated as a literal character rather than as a special character or string delimiter.
let quote = "He said, \"I learned from freeCodeCamp!\""; console.log(quote); // He said, "I learned from freeCodeCamp!" let apostrophe = 'It\'s a beautiful day'; console.log(apostrophe); // It's a beautiful day
Template Literals are string literals that allow you to embed expressions inside a string, using the syntax
let quote = `He said, "I learned from freeCodeCamp!"`; console.log(quote); // He said, "I learned from freeCodeCamp!"
With Template Literals, you don't need to use backslashes to escape characters. Instead, you simply wrap the string in backticks (
You can access over 180 of my articles by visiting my website. You can also use the search field to see if I've written a specific article.