When should I use double or single quotes in JavaScript?

Viewed 698742

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.

45 Answers

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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

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

Instead of:

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

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?

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.

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.

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"

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).

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>

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?

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.

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""

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

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

Related