Should I use 'single' or "double-quotes" for strings in JavaScript
You've seen both 'single quotes'
and "double quotes"
used for writing strings in JavaScript. You're wondering if they have any difference. Is there a preference over the other? Which way should you use in your code?
They are the same thing
In JavaScript, a string is a sequence of characters enclosed in single or double quotes. The choice of quoting style is up to the programmer, and either style has no special semantics over the other. There is no type for a single character in JavaScript - everything is always a string.
Strategic selection of the quote character can save you from escaping '
or "
characters inside the string. For example, when storing a HTML snippet in a variable, you can use "
for HTML attribute values if you use '
for enclosing the JavaScript string:
Remember, that in JSON, the only allowed quote character is the double quotes.
Single quotes are more common
Checking a few source repositories of popular JavaScript projects reveals that single quotes are favored over double quotes.
Project | Dominant quote style |
---|---|
lodash | ' - 99% of quotes |
chalk | ' - 100% of quotes |
react | ' - 90% of quotes |
request | ' - 97% of quotes |
commander.js | ' - 97% of quotes |
moment | ' - 90% of quotes |
express | ' - 92% of quotes |
tslib | " - 100% of quotes |
debug | ' - 97% of quotes |
node-fs-extra | ' - 98% of quotes |
axios | ' - 81% of quotes |
The fact that front-end libraries have more double quotes than the other libraries might have to do with the presence of HTML fragments.
Looking at a few style guides reveals a mixed approach, about half recommending single quotes and other half double quotes.
- prettier favors
"
double quotes by default - gjslint (Google Closure Linter) favors
'
single quotes - standard (an NPM package), favors
'
single quotes - jslint favors
"
double quotes by default - eslint favors
"
double quotes by default - TypeScript Contributors Coding Guidelines favor
"
double quotes
Stick to one and keep it consistent
To avoid making a choice every time you're about to write a string, you should pick one style and stick with it. If your team is still making up your mind - pick single quotes, they are more common. In ES6, you'll have a third option to enclose strings - the `backtick`
string.
Related articles
- Variable hoisting explained
- Should I use === or == equality comparison operator in JavaScript?
- Understanding the prototype property in JavaScript
Semantic Versioning Cheatsheet
Learn the difference between caret (^) and tilde (~) in package.json.