2189

console.log("double"); vs. console.log('single');

I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?

I thought they're pretty much interchangeable.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
aemkei
  • 10,846
  • 6
  • 35
  • 29
  • 144
    which is easier to read? alert("It's game time"); or alert('It\'s game time'); – Ryan Miller Jun 09 '11 at 16:10
  • 662
    How about this Ryan? `alert("It's \"game\" time.");` or `alert('It\'s "game" time.');`? – Francisc Oct 11 '11 at 18:37
  • 43
    If single quotes always used and occasionally double quotes where the literal contains single quote, then we will have to type far less shift buttons and our left little finger will give us blessings. But yes, as @arne said, for JSON double quote should be used. – IsmailS Oct 31 '11 at 15:46
  • 12
    Single quoting is easier to do when you're on a european keyboard (double quote is Shift+2 which isn't as sweet as tapping a single key conveniently by your right pinky). – Arne Apr 25 '12 at 20:46
  • 42
    @Arne There is no such a thing as an "European keyboard". E.g. the [German keyboard](http://en.wikipedia.org/wiki/Keyboard_layout#Austria_and_Germany) requires shift for both types of quotes. (But single quotes are easier.) – ANeves Jun 18 '12 at 15:53
  • 4
    Do not be religious about those (believe one is better than the other), use the one which avoids having to escape your string if possible as this will be easier to read. If you work with existing code use the existing convention if there is one. – Christophe Roussy Mar 21 '13 at 10:40
  • 2
    After reading through all the comments, knowing that I "should" choose a best practice, and knowing that I spend days and days coding in javascript, am I the ONLY person that ever catches myself using double quotes on one line and single quotes on the next line for no good reason without even thinking about it? The comments about using double quotes for JSON are important though, so I'm glad I randomly typed my question into Google and came across this. :) – streetlogics Oct 25 '13 at 21:45
  • 1
    If you are generating your JS from another programming language, your choice might be influenced by that. E.G, from C, which uses double quotes for its own strings, use single quote for your JS. For Delphi, it's the other way around. And so one ... – Mawg says reinstate Monica Feb 24 '14 at 09:38
  • 1
    Taking it from a different perspective.... using single quotes reduces number of keystrokes. As you don't need to hit "Shift" key.... :P – Manish Mar 22 '14 at 11:35
  • 2
    If you frequently embed HTML in strings, a single quote is a preferred option, that's one of the reasons why [Google Style Guide](https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Strings) recommends ' over " – Vitalii Fedorenko May 04 '15 at 19:38
  • 2
    Single quotes are better than double quotes because they use half as many pixels and are therefore quicker to display in your text editor. – Dan Bray Jan 06 '17 at 01:18
  • 1
    [As @user1429980 has answered below](https://stackoverflow.com/a/18041188/1211622), maybe double quotes are a better choice but I believe programmers tend to use single quotes more just because a single quote character saves you an extra key stroke (shift key). – Kamran Apr 29 '20 at 17:59

45 Answers45

1369

The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.

Using the other type of quote as a literal:

alert('Say "Hello"');
alert("Say 'Hello'");

This can get complicated:

alert("It's \"game\" time.");
alert('It\'s "game" time.');

Another option, new in ECMAScript 6, is template literals which use the backtick character:

alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);

Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.

Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ady
  • 4,726
  • 2
  • 21
  • 20
  • 104
    An important point to note with all code conventions - Define it once and stick with it. IOW, don't use double quotes someplace and single quotes elsewhere. – Cerebrus May 02 '09 at 08:03
  • 201
    @Cerebrus - I think flexibility is OK with this one. Sure pick a preferred style, but if you need to break away from the style to save escaping lots of quotes in one string. I'd be OK with that. – Martin Clarke May 02 '09 at 08:11
  • 12
    I don't think there's any reason to have to be consistent about it. There's no advantage to either one, and I don't think the readability is really affected whether or not you use ' in one place and " in another. – cdmckay May 02 '09 at 08:14
  • 3
    @Olly Hicks, interesting test!! Single quotes are actually several times faster than double quotes here in Chrome 13 (OSX). Interesting... – Ricket Sep 14 '11 at 23:48
  • Javascript was designed for web programmers and its creators wanted it to be as simple and flexible as possible. So I think unbounded data types and flexibility like single quote and double quote string declaration is result of that. – Jayram Jul 21 '13 at 10:51
  • 1
    Sublime Linter complains about double quote on strings so I started adopting single quotes fro strings – Cesar Vega Jun 25 '15 at 14:06
  • The problem with consistency is that nowadays people are often reusing code snippets from the Internet or other projects, thus it is frustrating to refactor all " to ' or vice versa after each copy->paste and it might introduce some bugs if you mess up escaping. I wish the entire Internet was consistent about quotes in Javascript... – JustAMartin Jul 30 '15 at 09:15
  • @Olly Hicks, I see quite a difference in timings for Chrome (51), but oddly enough there are a couple strange things: 1. If I hit the run button several times, the difference between the two timings decreases to 0 (and sometimes double quote is faster!). 2. If I put the double quote test first, the difference in timings is close to zero. – dshapiro Jul 21 '16 at 18:21
  • 18
    A little off-topic, but if people used correct typography, a lot of these discussions about escaping would be obsolete: `alert('It’s “game” time')` vs. `alert("It’s “game” time")` – doesn’t matter. You would only need to escape in the (rare) cases where the single or double prime sign `'`, `"` is actually appropriate. – jotaen Feb 04 '18 at 11:26
  • 2
    Consistency is indeed of prime importance. What irks me is the initial choice of a programmer to use single-quote in JS in the first place. If you're using Javascript you're also likely working with HTML, CSS and JSON and all of these use double-quotes. Therefore the initial 'programmer preference' choice to use single-quotes in JS for 'consistency' sake seems disingenuous if it's flouting consistency from the get-go by using a different quote style to existing HTML, CSS and JSON you'll be working with as a JS programmer. – Darren Evans Jan 02 '19 at 10:34
  • @DarrenEvans I standardized on single-quote for JS strings _**because**_ HTML uses double quotes... `someElement.innerHTML = '
    etc
    ';` vs `someElement.innerHTML = "
    etc
    ";`
    – Stephen P Dec 27 '20 at 20:06
  • Nowadays, tools like ESlint are enforcing it. So, if you have (and probably should use them btw) some styling conventions, you won't even need to ask yourself that kind of question, it will format it for you. ^^ – kissu Jan 03 '21 at 16:00
  • Another good argument for consistency is that some (many) auto-formatters help you to enforce consistency. They even reformat code you copied from another project that uses standards different from yours. – Budda May 06 '21 at 06:05
  • I'd actually like to ban the single quotes to make the difference between `foo("bar")` maximally different from `foo(\`bar\`)`. – Mikko Rantalainen Jan 26 '22 at 12:17
659

If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.

Arne
  • 2,906
  • 1
  • 21
  • 21
  • 7
    This is very relevant when working with jQuery.ajax calling into an ASP.NET service (Web Service, Page Method, or MVC). – Schmuli Mar 03 '11 at 11:46
  • 111
    The property names _within_ the JSON strings must be double-quoted, but a JSON string as a whole can be single-quoted: `var jsonString = '{"key1":"value1"}';` (Not that I recommend manually building JSON.) – nnnnnn Feb 09 '12 at 10:45
  • 1
    I also found this pretty relevant when creating `package.json` files for node.js. http://jsonlint.com/ could be used to validate json. – Antony Hatchkins Jul 07 '12 at 17:32
  • 54
    You shouldn't write JSON by hand if you can [`.stringify()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) it. – Camilo Martin Feb 03 '13 at 02:09
  • 26
    This right here is the best argument for always using double quotes. JSON should have double-quotes. The other answers are mostly giving the advice to "be consistent", which means if any one part of the language might realistically force a double quote, you should consistently use that double quote. – Josh from Qaribou Jul 14 '14 at 16:07
  • 19
    This is also relevant when working with multiple languages where nearly all other lanuguages (Java, C, C++, ...) use double quotes for strings and single quotes for chars. I prefer to use the same quoting across the board and so stick with double quotes for JS. With years of touch typing the extra key to shift for double quotes is entirely irrelevant, and if your coding is constrained by your typing then you need to practice typing properly. – Lawrence Dol Sep 24 '14 at 17:17
  • I like Lawrence Dol's comment as it's exactly how I work. Can someone cite where in the json standard I can find Arne's assertion that only double quotes are strictly supported? – mister270 Feb 05 '15 at 18:27
  • 2
    @mister270: http://json.org/ Specifically, the definition of a string, "A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes." – David Culp Apr 03 '15 at 16:41
  • 1
    Less pixel clutter == better – jkd Apr 13 '15 at 00:21
  • Note that this applies to JSON the datatype and not POJSO that are created within JavaScript itself which accept unquoted strings, single quoted strings, and double quote strings as keys. – brian Jun 29 '15 at 20:56
  • 2
    @JoshfromQaribou Actually I would say the opposite. If valid JSON required double-quotes, then the strings in your JavaScript should use single quotes, since this allows you to quote JSON strings without issue. – sdgfsdh Jul 27 '16 at 14:19
  • @sdgfsdh I use single quotes everywhere myself. I was just pointing out that if you're using it together this approach makes sense. I do think double-quotes feels a bit dated, since it made sense back in the days of JSONP hackery, but now that we have proper CORS we ought to respect JSON as its own filetype. There are other things that will get you in trouble if you try to treat JSON like it's ecma anyway (unquoted props, trailing commas) – Josh from Qaribou Jul 27 '16 at 14:58
  • As @JoshfromQaribou notes, this JSON point touches the best reason for single quotes: JSON is not JavaScript. JavaScript is easily confused with surrounding code/syntax like JSON, or Java,C,ASP,CF (server side). Using single quotes can help clarify what language (and location: client vs server side) one is in. I've strongly encouraged single quotes in JavaScript to help distinguish from server side code, a very educational pattern for newbies but also helpful to old guys, and JSON is another fine example. – Cris Mooney Aug 12 '16 at 19:04
  • 1
    @CrisMooney , and when people try to use single quotes in JSON, Java, C, ASP, etc. and their code doesn't compile and such because they were encouraged to use single quotes in JavaScript instead of staying consistent across languages... What then? Javascript not being JSON doesn't mean it should go all hipster on other languages. I don't know of a single non-esoteric language that enforces the use of single quote for strings. – snaplemouton Jul 17 '17 at 18:50
380

There is no one better solution; however, I would like to argue that double quotes may be more desirable at times:

  • Newcomers will already be familiar with double quotes from their language. In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ', the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.
  • Double quotes eliminate the need to escape apostrophes (as in contractions). Consider the string: "I'm going to the mall", vs. the otherwise escaped version: 'I\'m going to the mall'.
  • Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.

  • JSON notation is written with double quotes.

Nonetheless, as others have stated, it is most important to remain consistent.

Arc
  • 10,803
  • 4
  • 48
  • 71
user1429980
  • 6,450
  • 2
  • 42
  • 51
  • 5
    Your first point about English language is not always true and can change depending on the locality/house convention. Printed materials typically use single-quotes for speech and use other formatting for large blocks of quoted text. Your 'colloquial' meaning is not a useful definition of quotes for emphasis. Plus English users are in general very poor with quotation marks and apostrophes. – John Ferguson Jan 22 '15 at 13:24
  • 3
    @JohnFerguson, for that reason alone, it may be desirable to use double-quotes so as to make that differentiation (between apostrophes and quoted passages). – user1429980 Jan 22 '15 at 17:24
  • I'm all about pragmatism. Due to the fact that 1 in 100 strings that I type or uses has double quotes, and many, many more have apostrophes, I use doubles. At the end of the day, though, you should use the quote type that's 1) already in use in the project if you're a new developer to the project, or 2) use the one that you think makes more sense. – dudewad Nov 16 '15 at 17:43
  • Case in point-- what I just typed (there are multiple apostrophes, no double quotes ;) – dudewad Nov 16 '15 at 17:44
  • To add to @user1429980's third point, single quotes denotes a different datatype in Java and C. – Davina Leong Aug 02 '16 at 06:33
  • If you're building strings for JSON or HTML, you should use single quotes for the strings, because all the JSON properties and all the HTML attributes need double quotes. To avoid escaping them, the string must use single quotes. I find this to be the most common scenario, since JavaScript tends to work with JSON and HTML quite a bit. – Triynko Sep 13 '16 at 01:12
  • @Triynko, not necessarily; using single quotes in HTML is perfectly valid: ```let escapedHTML = "
    "```. For JSON, you should use single quotes when building, but in Javascript (context of this question), you will likely never encounter the need to do this because you will just build the JSON with objects.
    – user1429980 Sep 14 '16 at 02:06
  • This convinced me, and I want to add to the third point, "double quotes mean a string in many other languages". In Ruby, a string can be surrounded with single quotes or double, but in single quotes ``\`` is not interpreted as escape (as it is in JavaScript), so using double quotes makes it easier for Ruby user to switch to JavaScript where ``\`` means escape. Situation in Python is same as in JavaScript though. – Franklin Yu Dec 21 '16 at 01:38
  • ' is easier to confuse with \`, so stick with " so that you can see \` better. – OCDev Jan 13 '20 at 01:28
  • [Douglas Crockford](https://en.wikipedia.org/wiki/Douglas_Crockford) thinks we should [get rid of the single quote](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s). – Peter Mortensen Jul 18 '20 at 10:15
122

Section 7.8.4 of the specification describes literal string notation. The only difference is that DoubleStringCharacter is "SourceCharacter but not double-quote" and SingleStringCharacter is "SourceCharacter but not single-quote". So the only difference can be demonstrated thusly:

'A string that\'s single quoted'

"A string that's double quoted"

So it depends on how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.

Dave Jarvis
  • 29,586
  • 38
  • 176
  • 304
Gareth
  • 124,675
  • 36
  • 145
  • 155
  • @Gareth: I wasn't talking about specifications though, I was talking about possible performance impact. http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript/814376#814376 – Mathias Bynens May 02 '09 at 11:12
  • if you're putting enough apostrophes in your code to make up for how many times you need to hit shift+' then you're doing it wrong. – SgtPooki Aug 07 '14 at 20:36
  • 3
    What about `"{\"name\": \"Peter\"}"` vs `'{"name": "Peter"}'`? Admittedly, you could say this is the same difference, but it would certainly affect your decision in a different way than the example above. – Trevor Jun 16 '15 at 20:55
  • @MathiasBynens - That's an interesting observation that hasn't been relevant for at least a year, and maybe as long as 6 years. – ArtOfWarfare Aug 07 '15 at 20:22
  • 6
    One should use U+2019 for an apostrophe, not a vertical-single-quote – jjg Mar 14 '17 at 11:10
  • @MathiasBynens dunno what's your thoughts 9 years later.. but I would say that difference of *implementation* does not count as *specification* does, since that causes (caused?) little performance issues is some browser versions, returning expected values. If it's a bug causing unexpected behavior it'd worth a note though. – Andre Figueiredo Feb 20 '18 at 21:31
121

Single Quotes

I wish double quotes were the standard, because they make a little bit more sense, but I keep using single quotes because they dominate the scene.

Single quotes:

No preference:

Double quotes:

congusbongus
  • 12,079
  • 5
  • 68
  • 93
Alec Mev
  • 4,401
  • 4
  • 27
  • 43
  • 12
    Crockford now preferes double quotes. – Adam Calvet Bohl Sep 29 '16 at 05:16
  • 9
    airbnb now preferes double quotes – Suraj Jain Jan 12 '17 at 18:21
  • 20
    @SurajJain Source? [Airbnb](https://github.com/airbnb/javascript#strings--quotes) and [Google](https://google.github.io/styleguide/javascriptguide.xml?showone=Strings#Strings) style guides still list single as preferred. – Alec Mev Jan 12 '17 at 20:37
  • @OlegsJeremejevs https://github.com/jscs-dev/node-jscs/blob/master/presets/google.json They Do not use it , so i thought ... the link of google above when i opened it , and saw the file , they nowhere used the single quote – Suraj Jain Jan 13 '17 at 04:36
  • 6
    @SurajJain Ah, these are code style checker configs, written in JSON, which doesn't allow single quotes at all. Reading them is a nice way of comparing the choices made by different projects. – Alec Mev Jan 13 '17 at 09:38
  • @SurajJain Well, [Eloquent JavaScript](http://eloquentjavascript.net/) is well-regarded. Am not aware of something similar for CSS. Either way, you can look into online courses ([nice random list I just found](https://medium.com/@lovetrivedi/best-websites-to-learn-html-css-and-javascript-cebacb6088fa#.gop6ge62n)). – Alec Mev Jan 13 '17 at 10:37
  • Ok thanks , i will do so , and don't you get confused when you know these many language with syntax , and other concepts. – Suraj Jain Jan 15 '17 at 14:58
  • Facebook React uses single quotes [source](https://github.com/facebook/react/blob/master/.eslintrc.js#L36) – styfle Feb 23 '17 at 14:24
  • @styfle Thanks, added `eslint-config-fbjs-opensource`. – Alec Mev Feb 24 '17 at 09:36
  • 2
    Google now prefers single quotes – GabrielOshiro Mar 07 '19 at 19:19
  • The Douglas Crockford link is broken ([Google+ closed down](https://en.wikipedia.org/wiki/Google%2B#Shutdown_of_consumer_version)). [Here is a presentation](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s) (ConFoo Developer Conference 2017). – Peter Mortensen Jul 18 '20 at 10:18
  • I think `tslint` for TypeScript actually prefers single quotes by default. – Mikko Rantalainen Jan 26 '22 at 12:20
  • I prefer double quotes for two reasons: (1) JSON is close to simplified JavaScript and it supports double quotes only, and (2) ES6 supports *template strings* which use backtick (`\``) delimiter so it makes sense to avoid using nearly identifcal looking delimiter (single quote, `'`) for normal strings. – Mikko Rantalainen Jan 26 '22 at 12:25
62

I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:

/*
    Add trim() functionality to JavaScript...
      1. By extending the String prototype
      2. By creating a 'stand-alone' function
    This is just to demonstrate results are the same in both cases.
*/

// Extend the String prototype with a trim() method
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
};

// 'Stand-alone' trim() function
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
};

document.writeln(String.prototype.trim);
document.writeln(trim);

In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8), this will return the following:

function () {
    return this.replace(/^\s+|\s+$/g, '');
}
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

However, Firefox will yield a slightly different result:

function () {
    return this.replace(/^\s+|\s+$/g, "");
}
function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.

Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.

Conclusion: I think we need to do more research on this.

This might explain Peter-Paul Koch's test results from back in 2003.

It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.

2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mathias Bynens
  • 137,577
  • 52
  • 212
  • 242
  • 25
    If it's slightly faster in one browser to do it one way and slightly faster in another to do it the other way, it seems like the only guidance we can take away from that is that we should do whatever we like more because it will hurt some users and help others, and the amount of difference is likely to be imperceptible. "Premature optimization..." and all that. – Andrew Hedges May 03 '09 at 06:26
  • The thing is: it might be slightly faster in one browser (Firefox) while in other browsers, performance is unaffected. – Mathias Bynens May 03 '09 at 09:26
  • I fail to see how the way Firefox prints out functions is relevant here. This doesn't really answer the question. – Chris Calo Jan 10 '12 at 12:55
  • @ChristopherJamesCalo Did you actually read the answer? “[…] This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this ‘standard’.” – Mathias Bynens Jan 10 '12 at 17:23
  • 2
    I'm sorry my comment was not more constructive. I'm only saying that how the browser chooses to display its internal representation of the syntax probably has very little to do with how it is parsed and therefore probably isn't a reason to prefer one type of quotes over the other. Performance data comparing parse times for single and double quotes across browsers, on the other hand, would be more compelling. – Chris Calo Jan 14 '12 at 05:44
  • @ChristopherJamesCalo I’m just responding to the other comments here that claim both are the same and there’s no difference at all, other than syntax. – Mathias Bynens Jan 14 '12 at 16:29
  • I don't think you should choose a coding style based on a slight difference in browser parsing speeds. Javascript parsers change and if it's faster in one and slower in the other it's not really an optimization, right? I believe that if you want to optimize your code there are probably more important things you can do than changing quotes. – Renaat De Muynck Apr 17 '12 at 12:14
  • @RenaatDeMuynck I never said one is faster than the other — I just pondered the question. Either way, it shouldn’t affect anyone’s coding style, but it’s still interesting to think about it. – Mathias Bynens Apr 17 '12 at 12:44
  • 1
    This is an awesome answer, a break from the rest that just chirp 'They\'re the same they\'re the same'... You said _"Plus, in other programming languages, they're usually faster to use than double quotes"_, May I ask which languages? I have used regular langs like Java and C#, never seen one other than JS that accepts string literals in single quotes. The single quote enclosures are usually used only for character constants (only one char allowed). – ADTC Nov 27 '12 at 07:03
  • 1
    @ADTC I was referring to PHP. [This article](http://www.digital-web.com/articles/php_for_designers/) claims single quotes are faster than double quotes, because PHP has to interpret variables in string values with double quotes. I later heard that wasn’t true (anymore?), though. – Mathias Bynens Nov 27 '12 at 13:36
  • Thanks for your reply. I haven't done anything big in PHP and I kinda dislike it. Prefer JSP over it since I'm very familiar with Java. Never touched ASP :/. Anyway I thought you were referring to a language similar to Java, C#, etc coz I haven't come across such a case. – ADTC Nov 28 '12 at 08:32
  • 3
    AFAIK this was fixed in Firefox 17, Firefox used to do decompilation when doing `.toString` but now it returns the original copy. Modern firefox will not have this issue. – Benjamin Gruenbaum Mar 13 '14 at 10:14
  • 3
    Don't know about speed differences. But I'd like to note that "This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes." is nonsense. It UNparsed as if written with double quotes. That is it turned its internal representation (which just stores the string, not the quotes) into an human readable version, for which it happens to use one set of quotes. Anyhow, this seems to have changed, as per Benjamin's comment. – subsub Oct 11 '14 at 08:00
  • @ADTC I know this is an old post now, but I'd just like to add that PowerShell also has a difference in how it handles single and double quote strings. When you use single quotes, you are specifying a literal string, while the use of double quotes makes PS do string interpolation, resolving the variables inside the string. Thus, I assume that single quotes are probably faster (even though it might not be noticeable really), and I think the way they represent different semantics helps when you explicitly want interpolation or not. – julealgon Dec 08 '14 at 20:12
  • Not sure if this is some bug I'm not seeing or if there's something hinky when using pattern= attribute in Chrome; I have this on a text field: pattern='((12)|([2-9]|1[01]?)(\s(([13]\/4)|(1\/2)))?)\"?' This works. Doesn't work if I use double quotes. I tried double escaping the end quote in the pattern, but that didn't work, either. – Jeff Lowery Jan 15 '15 at 20:35
  • @JeffLowery In HTML `"` is escaped as `"` or similar, not as `\"`. – Mathias Bynens Jan 15 '15 at 22:20
  • Actually, \" is valid in an attribute value (when I said text field, I meant input of type=text); like I said, the pattern above is working in Chrome and Firefox and I guess now I will tack on a jsFiddle example... might try " as well. – Jeff Lowery Jan 15 '15 at 23:22
  • @JeffLowery Of course `pattern='\"'` is valid but the backlash is useless there. http://jsfiddle.net/bL37n14j/3/ – Mathias Bynens Jan 16 '15 at 18:16
34

If you're doing inline JavaScript (arguably a "bad" thing, but avoiding that discussion) single quotes are your only option for string literals, I believe.

E.g., this works fine:

<a onclick="alert('hi');">hi</a>

But you can't wrap the "hi" in double quotes, via any escaping method I'm aware of. Even &quot; which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox. " won't work either because at this point you're escaping for HTML, not JavaScript.

So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner. Someone please correct me if I'm wrong though.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Tom Lianza
  • 3,952
  • 4
  • 38
  • 50
  • 10
    Agreed about being arguably a bad thing, however if it must be done, I'm pretty sure URL-style encoding can be used eg `hi` - from memory this works, though it may have been in the href attribute instead `hi` – Graza Dec 16 '09 at 10:33
  • 2
    @PhiLho you're right about that... I was assuming that people were writing conventionally double-quoted HTML attributes, and weren't going to either (1) wholesale convert everything to single quotes, or (2) mix-and match single and double quoted attributes. But yes, you're right it's legal – Tom Lianza May 15 '11 at 16:18
  • @Robert I'm impressed that works. Obviously that is not valid JavaScript... if you were to run it in any interpreter other than a browser, it would be a syntax error. But, interesting anyhow. – Tom Lianza Jul 22 '11 at 05:42
  • 4
    @Tom Lianza, surely `alert("hi")` is not valid JavaScript. But values of attributes are encoded. http://www.w3.org/TR/html4/intro/sgmltut.html#didx-attribute – Robert Jul 22 '11 at 19:33
  • In HTML, using single-quotes is also allowed. However, in XML (and XHTML), double-quotes must be used for attributes. That's why people (myself included) usually use only double-quotes for attributes. – Denilson Sá Maia Aug 31 '11 at 15:27
  • 4
    Agreed with @Robert here. `"` is the correct way to escape a double quote inside of an HTML attribute. It works fine in Firefox. @Denilson, XML (and therefore XHTML) allows both single and double quotes. See the `AttValue` literal in the XML spec at http://www.w3.org/TR/REC-xml/#d0e888. – Chris Calo Jan 10 '12 at 13:06
  • 1
    @Pacener: Because it's, uh, not wrong. There is a convention in HTML to put attributes between double quotes. – Konrad Borowski May 25 '14 at 18:26
  • About the *only option thing* and this specific example you could do `hi` which also add these neat `/` characters around your string literal. – E. Sundin Jul 07 '16 at 00:43
  • [`hi`](https://jsfiddle.net/8ef36njq/). Wrapping the HTML attribute value in a quote is possible in HTML but not commonly used. – A1rPun Jun 23 '21 at 16:00
32

Technically there's no difference. It's only matter of style and convention.

Douglas Crockford recommends using single quotes for internal strings and double quotes for external (by external we mean those to be displayed to user of application, like messages or alerts).

I personally follow that.

UPDATE: It appears that Mr. Crockford changed his mind and now recommends using double quotes throughout :)

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mariusz Nowak
  • 30,462
  • 4
  • 34
  • 37
  • 13
    Douglas Crockford vs JQuery. Pick your poison. – Eric Rini Sep 28 '12 at 01:33
  • What is Crockford's reasoning for this? – BadHorsie Aug 02 '15 at 13:09
  • 1
    This is the convention I follow. It's more personal preference. I like using single quoted strings for internal stuff like jQuery selectors, and/or things like getElementById('id');, I just like the way it looks with single quotes. But, switch to double quotes for external text, since it often can contain internal quotes in the text. Also, it makes it easy to spot and differentiate between external vs internal strings if you are trying to find an error in one or the other. – adimauro Aug 27 '15 at 13:19
  • 4
    As of April 2016, Douglas Crockford [now recommends](https://plus.google.com/+DouglasCrockfordEsq/posts/EBky2K9erKt) using double quotes only, given that in practice, many developers found the internal versus external dichotomy difficult to use. – Thunderforge Aug 30 '16 at 20:27
  • Yes, see [this presentation](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s) (at 10 min 08 secs). – Peter Mortensen Jun 26 '20 at 19:23
  • @Thunderforge: This link is (effectively) broken. Google+ was shut down in 2019. – Peter Mortensen Jun 26 '20 at 19:25
  • @PeterMortensen Mr Crockford explained, that now he believes that double quotes should always be the choice, as it's on pair with string notation in JSON. I think it's very valid argument – Mariusz Nowak Jun 29 '20 at 10:23
30

Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.

Here are several factors that could influence your choice:

  • House style: Some groups of developers already use one convention or the other.
  • Client-side requirements: Will you be using quotes within the strings? (See Ady's answer.)
  • Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).
  • Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
  • Personal preference: You might think one or other style looks better.
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Kramii
  • 8,269
  • 4
  • 30
  • 37
  • Not true, `'` is `00100111` in binary, while `"` is `00100010` in binary. Thus, double quotes take up half as much power to store as single quotes. That's the difference right there. –  May 22 '17 at 21:59
  • [Douglas Crockford](https://en.wikipedia.org/wiki/Douglas_Crockford) thinks we should [get rid of the single quote](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s). – Peter Mortensen Jul 18 '20 at 10:09
20

Let's look what a reference does.

Inside jquery.js, every string is double-quoted.

So, beginning now, I'll use double-quoted strings. (I was using single!)

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Frederic
  • 81
  • 1
  • 2
  • 11
    Why is this down voted. This is a question of style and the best style is to be consistent and follow those who came before you. – Eric Rini Sep 28 '12 at 01:32
  • 2
    +1 The [jQuery API documentation](http://api.jquery.com/) does too. This was the single reason I settled for double quotes. Personally, I think answers that "it comes down to personal preference" are a bit flawed - best to find out a widely used convention and stick with it. And since I may want to copy and paste examples from jQuery (directly or indirectly), I don't want to have to replace the quotes every time. – Steve Chambers Feb 14 '14 at 11:53
  • 2
    Perhaps jQuery failed to follow the people before them (or really didn't care, like most other experts). ;) – James Wilkins Jun 10 '14 at 21:18
18

Just keep consistency in what you use. But don't let down your comfort level.

"This is my string."; // :-|
"I'm invincible."; // Comfortable :)
'You can\'t beat me.'; // Uncomfortable :(
'Oh! Yes. I can "beat" you.'; // Comfortable :)
"Do you really think, you can \"beat\" me?"; // Uncomfortable :(
"You're my guest. I can \"beat\" you."; // Sometimes, you've to :P
'You\'re my guest too. I can "beat" you too.'; // Sometimes, you've to :P

ECMAScript 6 update

Using template literal syntax.

`Be "my" guest. You're in complete freedom.`; // Most comfort :D
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
abhisekp
  • 3,062
  • 2
  • 28
  • 37
17

I hope I am not adding something obvious, but I have been struggling with Django, Ajax, and JSON on this.

Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.

So I agree with ady, but with some care.

My bottom line is:

In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.

My simple case was:

tbox.innerHTML = tbox.innerHTML + '<div class="thisbox_des" style="width:210px;" onmouseout="clear()"><a href="/this/thislist/'
                   + myThis[i].pk +'"><img src="/site_media/'
                   + myThis[i].fields.thumbnail +'" height="80" width="80" style="float:left;" onmouseover="showThis('
                   + myThis[i].fields.left +','
                   + myThis[i].fields.right +',\''
                   + myThis[i].fields.title +'\')"></a><p style="float:left;width:130px;height:80px;"><b>'
                   + myThis[i].fields.title +'</b> '
                   + myThis[i].fields.description +'</p></div>'

You can spot the ' in the third field of showThis.

The double quote didn't work!

It is clear why, but it is also clear why we should stick to single quotes... I guess...

This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.

So to answer the question:

Try to use single quotes while within HTML. It might save a couple of debug issues...

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
mariotti
  • 412
  • 1
  • 5
  • 23
  • 1
    I ran into a similar problem with ES6 string interpolation (backticks). My build system compiled it to a double-quoted string, which broke an Auth header that had been working with single quotes! – Jay Feb 12 '16 at 03:07
14

It's mostly a matter of style and preference. There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.

  • If you're coding in a company or team, then it's probably a good idea to follow the "house style".

  • If you're alone hacking a few side projects, then look at a few prominent leaders in the community. For example, let's say you getting into Node.js. Take a look at core modules, for example, Underscore.js or express and see what convention they use, and consider following that.

  • If both conventions are equally used, then defer to your personal preference.

  • If you don't have any personal preference, then flip a coin.

  • If you don't have a coin, then beer is on me ;)

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
cavalcade
  • 1,371
  • 14
  • 15
14

I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.

The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \n or \0 (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
garysb
  • 91
  • 1
  • 3
  • 16
    It's not that things used to be done one way and now they are done another. Different languages handle quotes differently, and some work as you describe. But this is a *JavaScript* question. Single and double quotes are treated identically in JavaScript (except for allowing the other type of quote to be used in a string without escaping). There is no question of double quotes allowing control characters or string interpolation. JavaScript doesn't work like that. Control characters and escape sequences work the same whichever type of quote you use. – Michael Geary Mar 15 '14 at 23:58
  • As an ex-Perl programmer, this is what I keep thinking though I know its irrelevant in JS. – zkent Dec 31 '14 at 16:23
  • @MichaelGeary, oh dear. That's what I was looking for in this question. Welcome from shells (i.e. Bash <3)... – Faither Dec 19 '21 at 20:01
13

If you are using JSHint, it will raise an error if you use a double quoted string.

I used it through the Yeoman scafflholding of AngularJS, but maybe there is somehow a manner to configure this.

By the way, when you handle HTML into JavaScript, it's easier to use single quote:

var foo = '<div class="cool-stuff">Cool content</div>';

And at least JSON is using double quotes to represent strings.

There isn't any trivial way to answer to your question.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
MetallimaX
  • 594
  • 4
  • 13
  • Has the implementation jshint changed? since the demo website seems to accept either without throwing any warnings/errors and I cannot find any options to constrain jshint to use either. Perhaps this answer is outdated or inaccurate? – Lea Hayes Nov 13 '15 at 09:44
  • if jshint raises an error for a double quoted string, its seriously broken. The JavaScript standard defines what is correct and not some broken linter. – Mecki Mar 23 '20 at 00:36
11

There isn't any difference between single and double quotes in JavaScript.

The specification is important:

Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.

It's like a benchmark if

a=b;

is faster than

a = b;

(extra spaces)

today, in a particular browser and platform, etc.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
11

Talking about performance, quotes will never be your bottleneck. However, the performance is the same in both cases.

Talking about coding speed, if you use ' for delimiting a string, you will need to escape " quotes. You are more likely to need to use " inside the string. Example:

// JSON Objects:
var jsonObject = '{"foo":"bar"}';

// HTML attributes:
document.getElementById("foobar").innerHTML = '<input type="text">';

Then, I prefer to use ' for delimiting the string, so I have to escape fewer characters.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Juan C. Roldán
  • 810
  • 1
  • 9
  • 19
11

One (silly) reason to use single quotes would be that they don't require you to hit the shift key to type them, whereas a double quote do. (I'm assuming that the average string doesn't require escaping, which is a reasonable assumption.) Now, let's suppose every day I code 200 lines of code. Maybe in those 200 lines I have 30 quotes. Maybe typing a double quote takes 0.1 seconds more time than typing a single quote (because I have to hit the shift key). Then on any given day, I waste 3 seconds. If I code in this manner for 200 days a year for 40 years, then I've wasted 6.7 hours of my life. Food for thought.

John Kurlak
  • 6,331
  • 7
  • 41
  • 58
  • 2
    I guess you are only referring to English keyboard layout here ... I have a German one, I have to hit shift for both. Anyway I dont see why pressing the shift key adds time to the process. I hit shift with the left hand, and press the quote key with the right. It happens at the same time, for me there is no difference. – codewandler Oct 16 '15 at 09:23
  • 1
    @codewandler There is still a cost of having to press the shift key even if you can press it in parallel to the " key. It forces you to move a finger away from its default position. For example, suppose you're typing: `var description = "This is a \"quick\" test";` on an English keyboard. For an English keyboard, your pinky finger must move from the left shift key up to the Q key on the top row instead of moving from the A key to the Q key. In other words, it must travel twice the distance. I'm not sure where the keys are on the German keyboard, but I'm sure there is an analogous example. – John Kurlak Oct 16 '15 at 16:55
  • 2
    @codewandler Also, having to type shift, even if I can do it in parallel, doesn't allow the left pinky finger to prepare to type the next character after " in whatever you're typing. – John Kurlak Oct 16 '15 at 16:58
  • 1
    The "time waste" idea is a bit silly, but the idea of less ergonomic strain (especially in the age of carpel tunnel syndrome, etc), makes it a nice gain, especially in cases where it otherwise doesn't matter. Given over 1,000 lines of code per day, this could save hundreds of daily pinky bends. – Beejor Jun 13 '18 at 18:24
  • There is something wrong if you literally type everything. There are copy&paste&modify, text templates (too well hidden in Visual Studio), [macro](https://www.instructables.com/id/Custom-Macro-Mechanical-Keypad/) [keyboards](https://www.youtube.com/watch?v=Arn8ExQ2Gjg) (physical), keyboard macros, and automation in various forms. – Peter Mortensen Jun 26 '20 at 19:54
11

Examining the pros and cons

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.
  • 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!\"'

Single quotes for internal strings and double for external. 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.

Divyesh Kanzariya
  • 3,291
  • 3
  • 39
  • 42
9

One more thing that you might want to consider as a reason for the shift from double quotes to single quotes is the increase in popularity of server side scripts. When using PHP you can pass variables and parse JavaScript functions using strings and variables in PHP.

If you write a string and use double quotes for your PHP you won't have to escape any of the single quotes and PHP will automatically retrieve the value of the variables for you.

Example:I need to run a JavaScript function using a variable from my server.

public static function redirectPage( $pageLocation )
{
    echo "<script type='text/javascript'>window.location = '$pageLocation';</script>";
}

This saves me a lot of hassle in having to deal with joining strings, and I can effectively call a JavaScript from PHP. This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in JavaScript.

Quote from PHP documents:

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Dodzi Dzakuma
  • 1,386
  • 2
  • 21
  • 38
  • +1, I do this in my MVC.Net project so that the double-quotes from C# don't interfere with the single quotes from javascript, and vice-versa. – DCShannon Mar 12 '15 at 01:31
  • 7
    I think if you are writing JavaScript onto your page from a PHP class method you have bigger problems. – BadHorsie Aug 02 '15 at 13:08
8

There are people that claim to see performance differences: old mailing list thread. But I couldn't find any of them to be confirmed.

The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Michiel Overeem
  • 3,724
  • 2
  • 23
  • 38
8

When using CoffeeScript I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.

"This is my #{name}"

ECMAScript 6 is using back ticks (`) for template strings. Which probably has a good reason, but when coding, it can be cumbersome to change the string literals character from quotes or double quotes to backticks in order to get the interpolation feature. CoffeeScript might not be perfect, but using the same string literals character everywhere (double quotes) and always be able to interpolate is a nice feature.

`This is my ${name}`
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
GijsjanB
  • 9,790
  • 4
  • 22
  • 26
  • To me the back tick is a clear winner in this contest, (almost) no presence inside common text strings, plus var interpolation – Simone Poggi Jul 27 '16 at 08:15
7

I've been running the following about 20 times. And it appears that double quotes are about 20% faster.

The fun part is, if you change part 2 and part 1 around, single quotes are about 20% faster.

//Part1
var r='';
var iTime3 = new Date().valueOf();
for(var j=0; j<1000000; j++) {
    r+='a';
}
var iTime4 = new Date().valueOf();
alert('With single quote : ' + (iTime4 - iTime3));  

//Part 2                
var s="";
var iTime1 = new Date().valueOf();
for(var i=0; i<1000000; i++) {
    s += "a";
}
var iTime2 = new Date().valueOf();
alert('With double quote: ' + (iTime2 - iTime1));
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Bastiaan Linders
  • 1,606
  • 2
  • 11
  • 14
  • 33
    Put another way, you've found that the later code runs fastest. This is the problem when doing micro-benchmarks. You have to account for the JS engine optimizing the code as it runs. (You'll see this same effect when benchmarking Java due to how the JIT works.) – David Phillips Jan 03 '11 at 06:46
  • 4
    first new Date is slow, add `var dummy_date = new Date()` to beginning – Lauri Oct 22 '12 at 10:31
  • 1
    The level of micro-optimization here is so silly that you could also argue that single quotes are faster to type, leading to faster development. – Beejor Jun 13 '18 at 18:28
6

I would use double quotes when single quotes cannot be used and vice versa:

"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'

Instead of:

'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
Gumbo
  • 620,600
  • 104
  • 758
  • 828
6

Now that it's 2020, we should consider a third option for JavaScript: The single backtick for everything.

This can be used everywhere instead of single or double quotes.

It allows you to do all the things!

  1. Embed single quotes inside of it: `It's great!`

  2. Embed double quotes inside of it: `It's "really" great!`

  3. Use string interpolation: `It's "${better}" than great!`

  4. It allows multiple lines: `

    This

    Makes

    JavaScript

    Better!

`

It also doesn't cause any performance loss when replacing the other two: Are backticks (``) slower than other strings in JavaScript?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
OCDev
  • 2,171
  • 3
  • 23
  • 35
  • [Douglas Crockford](https://en.wikipedia.org/wiki/Douglas_Crockford) suggests [getting rid of single quotes](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s). – Peter Mortensen Jun 26 '20 at 20:57
  • Backticks cannot be used in import statements. – Domino Nov 12 '21 at 21:48
  • @Domino is there a Node.js design reason for that? Or should we suggest to the maintainers that they add that? – OCDev Nov 13 '21 at 15:06
  • @OCDev `import` is part of the ECMAScript standard, it's not a Node-specific feature. As for the reason why they don't work with template litterals, it's because they are evaluated at load time before any JS code. Actually, the [ECMAScript standard](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-modules) doesn't even call them statements since they can only be at the root of a module. [`import()` calls](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-import-calls) however do support template litterals. – Domino Nov 15 '21 at 19:11
  • It seems that other restrictions might also come into play for the use of strings in import statements. Therefore, import statements could be thought of an exception to normal rules for strings and my convention for backtick syntax for strings simply doesn't apply in the context of import, unless you use import() calls. Furthermore, in other languages like C#, import/using statements do not wrap the module name in quotes at all. Thus, in an idiomatic sense, you don't even need to think of what you are passing to import as a string. The quotes are just an idiosyncratic part of import syntax. – OCDev Nov 16 '21 at 05:59
5

If you're jumping back an forth between JavaScript and C#, it's best to train your fingers for the common convention which is double quotes.

moomoo
  • 736
  • 8
  • 9
5

There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.

The speed difference legend might come from PHP world, where the two quotes have different behavior.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
PhiLho
  • 39,674
  • 6
  • 93
  • 131
  • And Ruby, I may add. Python has the same behavior as JavaScript: no difference is made between single/double quotes. – Damir Zekić Oct 28 '08 at 15:19
  • [Douglas Crockford](https://en.wikipedia.org/wiki/Douglas_Crockford) thinks we should [get rid of the single quote](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s). – Peter Mortensen Jul 18 '20 at 10:09
  • Well, some years later, we use single quotes everywhere in our JS (actually TS) code (ou backticks, of course). That mix well with double quotes used in HTML, when you have a JS/TS code in a template (eg. in Angular). – PhiLho Sep 24 '20 at 11:20
5

After reading all the answers that say it may be be faster or may be have advantages, I would say double quotes are better or may be faster too because the Google Closure compiler converts single quotes to double quotes.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mohsen
  • 61,836
  • 32
  • 154
  • 180
  • Do you know why it does that? – ma11hew28 Sep 16 '12 at 18:09
  • I don't know. Maybe it's a coding convention and nothing special. – Mohsen Sep 17 '12 at 03:19
  • Some context for the [Google Closure compiler](https://en.wikipedia.org/wiki/Google_Closure_Tools#Closure_Compiler): *"The Closure Compiler is a tool for making JavaScript download and run faster, at the expense of human readability. It does not compile from JavaScript to machine code, but rather compiles from JavaScript to more efficient JavaScript. It parses JavaScript, analyzes it, removes dead code and rewrites and minifies what is left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls. It supports transpiling some ECMAScript 6"* – Peter Mortensen Jun 28 '20 at 16:22
3

If your JavaScript source is

elem.innerHTML="<img src='smily' alt='It\'s a Smily' style='width:50px'>";

the HTML source will be:

<img src="smiley" alt="It's a Smiley" style="width:50px">

Or for HTML5

<img src=smiley alt="It's a Smiley" style=width:50px>

JavaScript allows arrays like that:

var arr=['this','that'];

But if you stringify it, it will be for compatibility reasons:

JSON=["this","that"]

I'm sure this takes some time.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
B.F.
  • 453
  • 6
  • 8
3

Just to add my two cents: In working with both JavaScript and PHP a few years back, I've become accustomed to using single quotes so I can type the escape character ('') without having to escape it as well. I usually used it when typing raw strings with file paths, etc.

Anyhow, my convention ended up becoming the use of single quotes on identifier-type raw strings, such as if (typeof s == 'string') ... (in which escape characters would never be used - ever), and double quotes for texts, such as "Hey, what's up?". I also use single quotes in comments as a typographical convention to show identifier names. This is just a rule of thumb, and I break off only when needed, such as when typing HTML strings '<a href="#"> like so <a>' (though you could reverse the quotes here also). I'm also aware that, in the case of JSON, double quotes are used for the names - but outside that, personally, I prefer the single quotes when escaping is never required for the text between the quotes - like document.createElement('div').

The bottom line is, and as some have mentioned/alluded to, to pick a convention, stick with it, and only deviate when necessary.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
James Wilkins
  • 6,173
  • 2
  • 42
  • 69
3

The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.

Andrew Hedges
  • 21,426
  • 16
  • 65
  • 79
  • No practical difference? Can you prove it? – Mathias Bynens May 02 '09 at 08:21
  • 7
    The burden of proof is on the guy asserting there's a difference when the language doesn't. – Anonymous May 02 '09 at 09:10
  • 2
    Wisdom; the language doesn't specify a difference, which means there is no *syntactical* difference. However, there seems to be a cross-browser difference which appears to indicate performance implications: http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript/814376#814376 People saying it doesn't matter what quotes you use, are talking about syntax. I'm talking about practical implementation in different browsers. – Mathias Bynens May 02 '09 at 13:21
  • 6
    I read your comment on that other thread. Are you serious? How much faster is JavaScript that uses double quotes? 0.00001 second per line? I think the burden of proof is on you to show a test where it matters in any significant way whether one uses double or single quotes. "One might think" isn't evidence. By the way, I used to always use double quotes until I noticed that all of the JavaScript in Apple Dashboard widgets is single quoted. If it's good enough for Apple... – Andrew Hedges May 03 '09 at 06:24
  • [Douglas Crockford](https://en.wikipedia.org/wiki/Douglas_Crockford) thinks we should [get rid of the single quote](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=10m8s). – Peter Mortensen Jul 18 '20 at 10:05
3

You can use single quotes or double quotes.

This enables you for example to easily nest JavaScript content inside HTML attributes, without the need to escape the quotes. The same is when you create JavaScript with PHP.

The general idea is: if it is possible use such quotes that you won't need to escape.

Less escaping = better code.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
JJTalik
  • 86
  • 4
3

It is just a matter time for me. A few milliseconds lost of my life every time I have to press the Shift key before every time I'm able to type ".

I prefer ' simply because you don't have to do it!

Other than that, you can escape a ' inside single quotes with backslash \'.

console.log('Don\'t lose time'); // "Don't lose time"

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ovidb
  • 1,598
  • 12
  • 17
2

For me, if I code in a Vim editor and if something is enclosed in single quotes, I can double-click to select only the text within the quotes. Double quotes, on the other hand, include the quote marks which I find annoying when I want to do some quick copy and pasting.

E.g. 'myVar' double-click in the Vim editor copies: >myVar< "myVar" literally copies: >"myVar"< and when I paste, I have to delete the quote marks on either side.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Jason
  • 710
  • 9
  • 18
  • 1
    This is configurable in most terminals (e.g. gnome-terminal: Edit->Profile->General->Select-by-word characters), and in gVim (http://superuser.com/a/387060/33415). – Beni Cherniavsky-Paskin Aug 29 '13 at 01:17
2

I use single quotes most of the time, because when developing in PHP, single quoted-string are in no way altered, which is what I want. When I use

echo "$xyz";

In PHP, $xyz gets evaluated, which is not what I want. Therefore I always use ' instead of " when it comes to web development. So I ensure at least string-consistency when it comes to PHP/JavaScript.

Unfortunately this can't be done in Java or Objective-C, where '' stands for character and "" stands for string. But this is another question.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Bruno Jennrich
  • 339
  • 5
  • 4
  • Re *"[JScript](https://en.wikipedia.org/wiki/JScript)"*: Do you mean *"JavaScript"*? – Peter Mortensen Jun 26 '20 at 20:46
  • i use "jscript" and "javascript" interchangeably... as jscript is/was a language developed by microsoft is a subset of javascript but the differences don't fall into account here – Bruno Jennrich Jun 29 '20 at 16:20
1

If you use PHP to generate JavaScript code you should use the following declaration.

let value = "<?php echo 'This is my message, "double quoted" - \'single quoted\' ?>";

The output will be:

This is my message, "double quoted" - 'single quoted'

For some reasons it is recommend to use single quotes rather than double quotes in PHP.

For the normal behaviour in JavaScript it is recommend to use single quotes.

var value = 'This is my message';
document.getElementById('sample-text').innerHTML = value;
<span id="sample-text"></span>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Gordon
  • 69
  • 4
1

I prefer to use the single quote, '. It is easier to type and looks better.

Also, let’s remember that straight quotes (single and double) are a mistake in good typography. Curly quotes are preferable, so instead of escaping straight quotes I prefer to use the correct characters.

const message = 'That\'s a \'magic\' shoe.' // This is wrong
const message = 'That’s a ‘magic’ shoe.' // This is correct

https://practicaltypography.com/straight-and-curly-quotes.html

Can someone add a smart-quote feature to Visual Studio Code, please?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
lolol
  • 4,169
  • 3
  • 34
  • 49
1

I think it's important not to forget that while Internet Explorer might have zero extensions/toolbars installed, Firefox might have some extensions installed (I'm just thinking of Firebug for instance). Those extensions will have an influence on the benchmark result.

Not that it really matters since browser X is faster in getting elementstyles, while browser Y might be faster in rendering a canvas element (hence why a browser "manufacturer" always has the fastest JavaScript engine).

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Jozzeh
  • 813
  • 10
  • 28
0

I think this is all a matter of convenience/preference.

I prefer double quote because it matches what C# has and this is my environment that I normally work in: C# + JavaScript.

Also one possible reason for double quotes over single quotes is this (which I have found in my projects code): French or some other languages use single quotes a lot (like English actually), so if by some reason you end up rendering strings from the server side (which I know is bad practice), then a single quote will render wrongly.

The probability of using double quotes in a regular language is low, and therefore I think it has a better chance of not breaking something.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Kat Lim Ruiz
  • 2,251
  • 2
  • 24
  • 30
0

Personally I prefer single quotes for the sake of readability. If I'm staring at code all day it's easier to see the words with just single quotes as opposed to double quotes.

Easier to read as demonstrated here:

'easy to read'

"harder to read"

""hardest to read""

Anthony
  • 12,124
  • 13
  • 54
  • 68
0

In addition, it seems the specification (currently mentioned at MDN) doesn't state any difference between single and double quotes except closing and some unescaped few characters. However, template literal (`) assumes additional parsing/processing.

A string literal is 0 or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values...

Source: https://tc39.es/ecma262/#sec-literals-string-literals

Faither
  • 698
  • 3
  • 14
  • 25
0

Single quotation (') uses one keyboard key, but double quotation uses two keys (shift+'). So saving the number of keys press is also an advantage! (:

Nabi K.A.Z.
  • 8,401
  • 6
  • 51
  • 69
-1

As stated by other replies, they are almost the same. But I will try to add more.

  1. Some efficient algorithms use character arrays to process strings. Those algorithms (browser compiler, etc.) would see " (#34) first before ' (#39) therefore saving several CPU cycles depending on your data structure.
  2. " is escaped by anti-XSS engines
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Eugene Ramirez
  • 2,903
  • 2
  • 21
  • 17
  • 2
    (1) sounds like pure speculation. An efficient tokenizer wouldn't use a dumb `if 0x30 ... else if 0x31 ... else if ...` structure. A compiler would translate a switch into a balanced tree of branches (so hard to say which is cheaper if at all), or a jump table (so all cost the same). And there are weirder ways e.g. bit tricks to scan for a char in a whole word at once. *In any case, this would be negligble and not something to consider when deciding how to write your code*. – Beni Cherniavsky-Paskin Aug 29 '13 at 00:44
  • speculation at best. I tried to look this up and hit a dead end. Would be interested to see where this algo is referenced – Spets Oct 10 '16 at 06:54
-2

For use of JavaScript code across different languages, I've found single quotes to consistently require less code tweaking.

Double quotes support multi-line strings.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
aelgoa
  • 1,113
  • 1
  • 8
  • 23
-4

The best practice is to use double quotes ("") first and single quotes ('') if needed after. The reason being is that if you ever use server-side scripting you will not be able to pull content from a server (example SQL queries from a database) if you use singles quotes over double.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Jules
  • 1
  • Not sure about that last part. If proper measures are made to escape the string to prevent SQL injection (a security risk), I think any quote is acceptable. Characters should not be passed over verbatim. – James Wilkins Jun 12 '14 at 19:05