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


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

…but this can get complicated…

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

Another option, new in ES6, are Template literals which use the back-tick character:

alert(`Use "double" and 'single' quotes in the same string`);
alert(`The escape the ` back-tick character in a string`);

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


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.


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.

    链接地址: http://www.djcxy.com/p/8420.html

    上一篇: ASP.NET MVC控制器可以返回一个图像吗?

    下一篇: 何时在JavaScript中使用双引号或单引号?