Monday 27 June 2016

string - When to use double or single quotes in JavaScript?




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



I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.


Answer



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 ES6, are Template literals which use the back-tick 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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...