views:

7817

answers:

15

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.

+27  A: 

I wouldn't say there is a preferred method, you can use either. However If you are using one form of quote in the string, you might want to use the other as the literal.

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

The most likely reason is programmer preferance / API consistency.

Ady
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
@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
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
"No advantage to either one"? Prove it.
Mathias Bynens
@Mathias Bynens: You cannot prove the inexistence of something. Prove that there *is* an advantage to either one, that's the way to go. ;)
Pascal
+1  A: 

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 inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.

Michiel Overeem
Though attributes can be as well surrounded with single quotes :)
Damir Zekić
Your right, I thought that xml and xhtml prescribed double quotes surrounding attributes, but single quotes are allowed to.
Michiel Overeem
A: 

There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JS 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.

PhiLho
And Ruby, I may add.Python has the same behavior as JavaScript: no difference is made between single/double quotes.
Damir Zekić
+42  A: 

You want to use single quotes since you'll save bandwidth by not sending the extra pixels ;).

kamens
I LOL'd! Had to up it :D
Damir Zekić
Heh, LOL++ from me
ephemient
Best answer in a long time LOL!
Miquel
Yet another +1 for the LOL factor. I can't say I really want to encourage this sort of reply on SO, but what the heck.
Seth Petry-Johnson
+1 for obvious speed advantage
Frank
+1 for supporting 'Save the Pixelz'!
vfilby
Well.... when considering climate change the double quote might be better, for the CRT monitor users out there. Has an adverse effect on white text on black backgrounds though....Yeah ! single quo.... o wait, the quotes in code are not displayed anywa..... *mumbles* this is going nowhere...
Bastiaan Linders
@Bastiaan: Single `'quotes'` indeed can be displayed.
Atømix
+6  A: 

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

Here are several factors that could influence your choise:

  • 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 java-script so that the scripts can be built server-side (VB.Net uses double-quotes for strings, so the java-script 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 thing one or other style looks better.
Kramii
A: 

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
No practical difference? Can you prove it?
Mathias Bynens
The burden of proof is on the guy asserting there's a difference when the language doesn't.
Anonymous
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
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
+4  A: 

The only difference is demonstrated in the following:

'A string that\'s single quoted'

"a string that's double quoted"

So, it's only down to how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.

Gareth
How can you be sure that's the only difference?
Mathias Bynens
Gareth makes a good point. I didn't think of this
Charlie Somerville
@Mathias - section 7.8.4 of the specification [http://www.ecma-international.org/publications/standards/Ecma-262.htm] describes literal string notation, the only difference is that DoubleStringCharacter is "SourceCharacter but not double-quote" and SingleStringCharacter is "SourceCharacter but not single-quote"
Gareth
@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
@Mathias - Ok, I see your point, and while I would love to think that JavaScript programs are optimized to the point where this makes a measurable difference (and even then, this is left to the whims of a particular interpreter), I'm just a little cynical about that.
Gareth
+5  A: 

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 IE7 and IE8), 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.

Edit: 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.

Mathias Bynens
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
The thing is: it might be slightly faster in one browser (Firefox) while in other browsers, performance is unaffected.
Mathias Bynens
A: 

Double quotes will wear your shift key out faster :)

Jeremy Huiskamp
Not on Azerty, buddy.
Mathias Bynens
A: 

I think it's important not to forget that while IE might have 0 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)

Jozzeh
A: 

A modest proposal:

Let's start a movement to change code syntax (for all programming languages) to support paired quotation marks (distinctive open and close quote symbols) such as the Guillemet (used by the French, Spanish, Italians, Norwegians, Russians, et al.) http://en.wikipedia.org/wiki/Guillemets

Any paired symbols would work, but they should be easily generated from most keyboards. Since parentheses, square brackets, curly braces, and the back quote are already in wide use for other purposes, I suggest we use double angle brackets to simulate the Guillemet << like this >>.

If we did this, we would never again need to escape a quotation mark!

+2  A: 

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

ex, 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 app, I think single quotes are the winner. Someone please correct me if I'm wrong though.

tlianza
Agreed about being arguably a bad thing, however if it must be done, I'm pretty sure URL-style encoding can be used eg `<a onclick="alert(%22hi%22);">hi</a>` - from memory this works, though it may have been in the href attribute instead `<a href="javascript:alert(%22hi%22);">hi</a>`
Graza
+2  A: 

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

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

Instead of:

'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
Gumbo
A: 

there is no difference between single and double quotes in javascript.

specification is important:

maybe there are performance diffs, but they are absolutely minimum and can change everyday according to browsers' implementation. further discussion is futile unless your js application is hundreds of thousands long.

it's like benchmark if

a=b;

is faster than

a = b;

(extra spaces) today, in a particular browser and platform, etc.

A: 

i've been running the following about 20 times. and it appears that Double quotes are about 20% faster. 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));
Bastiaan Linders