Tuesday 22 October 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...