When should I use double or single quotes in JavaScript?

前端 未结 30 3366
攒了一身酷
攒了一身酷 2020-11-21 05:02

console.log("double"); vs. console.log(\'single\');

I see more and more JavaScript libraries out there using single quotes when ha

30条回答
  •  攒了一身酷
    2020-11-21 05:34

    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.

提交回复
热议问题