[javascript] When should I use double or single quotes in JavaScript?

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.

This question is related to javascript string conventions

The answer is


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.


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.


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.


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.


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.


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.


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


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

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:


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


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

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

Instead of:

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

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.


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.


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.


Examining the pros and cons

In favor of single quotes

  • Less visual clutter.
  • Generating HTML: HTML attributes are usually delimited by double quotes.

_x000D_
_x000D_
elem.innerHTML = '<a href="' + url + '">Hello</a>';
_x000D_
_x000D_
_x000D_ However, single quotes are just as legal in HTML.

_x000D_
_x000D_
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
_x000D_
_x000D_
_x000D_

Furthermore, inline HTML is normally an anti-pattern. Prefer templates.

  • Generating JSON: Only double quotes are allowed in JSON.

_x000D_
_x000D_
myJson = '{ "hello world": true }';
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
    "He said: \"Let's go!\""_x000D_
    'He said: "Let\'s go!"'_x000D_
    "He said: \"Let\'s go!\""_x000D_
    'He said: \"Let\'s go!\"'
_x000D_
_x000D_
_x000D_

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.


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.


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.


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.


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.


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


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


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


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.


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?


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.


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


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


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

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.


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


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.

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.


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.


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


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.


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.


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}`

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

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

Instead of:

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

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.

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.

_x000D_
_x000D_
var value = 'This is my message';
document.getElementById('sample-text').innerHTML = value;
_x000D_
<span id="sample-text"></span>
_x000D_
_x000D_
_x000D_


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.


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.


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?


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}`

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.


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.


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

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?


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.


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

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.


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.


Examining the pros and cons

In favor of single quotes

  • Less visual clutter.
  • Generating HTML: HTML attributes are usually delimited by double quotes.

_x000D_
_x000D_
elem.innerHTML = '<a href="' + url + '">Hello</a>';
_x000D_
_x000D_
_x000D_ However, single quotes are just as legal in HTML.

_x000D_
_x000D_
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
_x000D_
_x000D_
_x000D_

Furthermore, inline HTML is normally an anti-pattern. Prefer templates.

  • Generating JSON: Only double quotes are allowed in JSON.

_x000D_
_x000D_
myJson = '{ "hello world": true }';
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
    "He said: \"Let's go!\""_x000D_
    'He said: "Let\'s go!"'_x000D_
    "He said: \"Let\'s go!\""_x000D_
    'He said: \"Let\'s go!\"'
_x000D_
_x000D_
_x000D_

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.


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.


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


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.


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.


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're jumping back an forth between JavaScript and C#, it's best to train your fingers for the common convention which is double quotes.


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.


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


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.


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.


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


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.


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.


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"


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:


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.


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.


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"


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.


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.


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.


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.


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.


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


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.


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


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

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.


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.


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


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.


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.


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

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


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.

_x000D_
_x000D_
var value = 'This is my message';
document.getElementById('sample-text').innerHTML = value;
_x000D_
<span id="sample-text"></span>
_x000D_
_x000D_
_x000D_