Tuesday, 4 July 2017

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...