Search code examples
javascriptstring

Are double quotes and single quotes interchangeable for string literals? (JavaScript)


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