HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Are double quotes and single quotes interchangeable for string literals in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
doublequotesinterchangeableareandforsinglestringliteralsjavascript

Problem

Consider the following two alternatives:

  • console.log("double");



  • console.log('single');



The former uses double quotes around the string, whereas the latter uses single quotes around the string.

I see more and more JavaScript libraries out there using single quotes when handling strings.

Are these two usages interchangeable? If not, is there an advantage in using one over the other?

Solution

The most likely reason for use of single vs. double quote 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.

Code Snippets

alert('Say "Hello"');
alert("Say 'Hello'");
alert("It's \"game\" time.");
alert('It\'s "game" time.');
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);

Context

Stack Overflow Q#242813, score: 1444

Revisions (0)

No revisions yet.