'abc' === "abc" // true
So, what are the main points of single or double quotes?
- Both single and double quotes declare a value of a variable is a string.
- If you “open a string” with one type of quote, close it with that same one.
Each type of quote must escape its own type inside of a string
You can use double quotes with a single ( ‘ ) quote in the middle of a string, but you cannot use double quotes in the middle of a string – if you do, you’ll have to escape them. And the same goes for single quotes: you can use single quotes with double ( ” ) quotes in the middle of a string, but you cannot use single quotes in the middle of a string – if you do, you’ll have to escape them.
So, each type of quote – either single or double – must escape its own type inside of a string.
Single quotes must “escape” single quotes
When you’re using single quotes (”) to create a string literal, you have to use backslash (\’) to escape the single quote character, like so:
var escape = 'No, I won\'t do "that".';
We escaped grammatically correct won’t because we started and ended a string with single quotes, but as you can see we used double quotes inside a single-quoted string without any issues.
Double quotes must “escape” double quotes
When you’re using double quotes (” “) to create a string literal, you have to use backslash (\”) to escape the double-quote character, like so:
var escape = "No, I won't do \"that\".";
So, this time we have no issues with won’t because we started and ended a string with double quotes, but as you can see we used backslash to escape double quotes with “that”.
You decide what is more convenient for you. Personally, I prefer single quotes, but it is really up to you what is your preference.
var single_html = '<div id="something_we_write_in_div"></div>';
But if you use double quotes, you must escape those that are nested and that can get annoying, at least to me. See what I am talking about:
var double_html = "<div id=\"something_we_write_in_div\"></div>";
Are there any advantages to using double quotes? Absolutely. Besides JSON files that won’t give you additional work with quotes, another advantage would be when writing in English – you won’t have to escape apostrophes when using double-quotes.