41

Possible Duplicate:
When to Use Double or Single Quotes in JavaScript
Are there differences between ' and "

I am wondering if there is a difference between using single quotes vs double quotes in JavaScript (JQuery selectors etc.).

Both seem to work just fine, so is there a difference?

0

4 Answers 4

67

The difference is that you don't need to escape single quotes in double quotes, or double quotes in single quotes. That is the only difference, if you do not count the fact that you must hold the Shift key to type ".

4
  • 37
    On German keyboards, you have to use the Shift key for both.
    – Gumbo
    Mar 31, 2012 at 21:44
  • 6
    Gumbo This is also true for a french keyboard configuration.
    – Samuel
    Mar 20, 2013 at 12:49
  • 1
    On French keyboards, you have to use the Shift key for none :)
    – sp00m
    Apr 4, 2016 at 10:14
  • 2
    I wish SO had the option to favorite answers in addition to questions... Jun 21, 2017 at 15:39
24

It doesn't matter unless you're trying to write JSON, in which case you must use double quotes for object literals.

2
  • 7
    Could you please elaborate? Maybe with some examples? May 1, 2017 at 16:01
  • 1
    @JeffAxelrod: the text {'abc': 123} is an example of invalid JSON. JSON refuses to delimit text like that with single quotes. (It is technically not valid JavaScript by itself, you would have to write const x = {'abc': 123} to make it valid JS. If you don't do that the leading { is parsed as a beginning of a code block.) the text {"abc": 123} is a valid JSON string.
    – CR Drost
    Mar 25, 2019 at 19:22
12

There is no special difference between single and double quotes (like it is in PHP).

The only actual difference is that you can write a double quote " in a single-quoted string without escaping it, and vice versa.

So, if you are going to output some HTML in your JavaScript, like this:

<div id = "my_div"></div>

single quotes are more useful :-)

4
  • 7
    And if you have an HTML output like <div id = 'my_div'></div>, double quotes are more useful.
    – Gumbo
    Mar 31, 2012 at 21:46
  • 1
    Sure :-) I used the example because double quotes are more common. But yes, the point is - use whatever quotes are not present in the string.
    – Imp
    Mar 31, 2012 at 21:49
  • 6
    I agree with Imp but whatever quote style you use, the golden rule is to be consistent. Mar 31, 2012 at 21:57
  • 1
    In php, variables within double quoted literals are evaluated. They aren't within single quotes. Jan 26, 2017 at 16:53
3

They work the same, but they must match. You cannot start a string with a single and end with a double, or the opposite. Other than that, they are interchangeable.

Not the answer you're looking for? Browse other questions tagged or ask your own question.