JavaScript: single quotes or double quotes?

[2012-09-17] dev, javascript, jslang, jsstyle
(Ad, please don’t block)
Today, I’ve asked on Twitter:
JavaScript: single quotes versus double quotes. Any preferences?
And I got great answers. Two funny examples:
  • “Is this a ploy to get lots of @-replies?” – @tobie
  • “Using single quotes saves bandwidth because you don’t have to send the extra pixels. #performance #truestory” – @mathias
Among the respondents, there was a slight preference for single quotes.

Examining the pros and cons

Let’s examine the arguments in favor of each kind of quote.

In favor of single quotes

  • Less visual clutter.
  • Generating HTML: HTML attributes are usually delimited by double quotes.
        elem.innerHTML = '<a href="' + url + '">Hello</a>';
    
    However, single quotes are just as legal in HTML.
        elem.innerHTML = "<a href='" + url + "'>Hello</a>";
    
    Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
  • Generating JSON: Only double quotes are allowed in JSON.
        myJson = '{ "hello world": true }';
    
    Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.

In favor of double quotes

  • “Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.” – @wiredearp
  • Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
  • If you want code to be valid JSON, you need to use double quotes.

In favor of both

There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
    "He said: \"Let's go!\""
    'He said: "Let\'s go!"'
    "He said: \"Let\'s go!\""
    'He said: \"Let\'s go!\"'
@medikoo proposes the following convention:
Single quotes for internal strings and double for external.
Nice idea. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.

In favor of neither

For human language, you want to use curly quotes and apostrophes. For example:
    He said: “Let’s go”
That’s the typographically decent thing to do.

What do JavaScript engines prefer?

Chrome console – double quotes:
    > 'abc'
    < "abc"
Firefox console – double quotes:
    19:39:39.659 ❙ ◀ 'abc'
    19:39:39.662 ❙ ▶ "abc"
Node.js REPL – single quotes:
    > "abc"
    'abc'