Single-Quotes Vs Double-Quotes in JavaScript

Single-Quotes Vs Double-Quotes in JavaScript

2019, Nov 20    

JavaScript, allows you to use either single quotes ('') or double quotes ("") to create a string literals.

Both Have the Same Qualities

They are essentially the same.

console.log('abc' === "abc"); // true

A single quoted string can have double quotes within it without having to escape them.

console.log('Single quotes with a double ( " ) quote in the middle.');

A double quoted string can have single quotes without escaping them.

console.log("Double quotes with a single ( ' ) quote in the middle.");

Each type must escape their own type.

console.log('single quotes ( \' ) must escape a single quote');

console.log("double quotes ( \" ) must escape a double quote");

Pros of Using Single Quotes

One popular argument for single quotes is when you have to write html within JavaScript.

If you use single quotes you can write as following.

const html = '<div id="some_div"></div>';

If you use double quotes you must escape each nested "

const html = "<div id=\"some_div\"></div>";

which can get annoying or you could use single quotes within the html string.

Pros of Using Double Quotes

Remember that JSON only allows double quotes.

{
  "in_json": "You use only double quotes."
}

Single Quotes are More Common

A few repositories of popular JavaScript projects reveals that single quotes are favored over double quotes.

+------------+----------------------------------+
| Projects   | Dominant of Single Quotes        |
+------------+----------------------------------+
| async      | Single-Quotes ('') 76% of quotes |
| express    | Single-Quotes ('') 92% of quotes |
| lodash     | Single-Quotes ('') 73% of quotes |
| request    | Single-Quotes ('') 97% of quotes |
| underscore | Single-Quotes ('') 78% of quotes |
| angular    | Single-Quotes ('') 58% of quotes |
| react      | Single-Quotes ('') 52% of quotes |
+------------+----------------------------------+

You can see that front-end libraries (React, Angualar, …) have more double quotes than the other libraries as might have to do with the presence of HTML fragments.

Let’s take a look at a few style guides you can see that about half recommend single quotes and other half double quotes.

Summary

You should define one standard style and stick with it. I recommend single quotes ('') as a solid standard and more common.

In ES6, there is another option to create a string literals using Template literals.

References

Thanks for reading ❤
Say Hello! Twitter | Github | LinkedIn | Facebook | Instagram

Like ❤️

'Single-Quotes' Vs "Double-Quotes" in JavaScript