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.
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.
Not sure if this is relevant in todays world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.
The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like
\n
or\0
(not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in cpu cycles for processing the string).In favor of single quotes
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.
In favor of double quotes
In favor of both
There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.
The only difference is demonstrated in the following:
So, it's only down to how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.
If your JS source is:
The HTML source will be:
or for HTML5
JS allows arrays like that:
But if you stringify it, it will be for compatibly reason:
I'm sure this takes some time.
Talking about performance, quotes will never be your bottleneck, however, the performance is the same in both cases.
Talking about coding speed, if you use
'
for delimiting a string, you will need to escape"
quotes. You are more likely to need to use"
inside the string, in example:Then, I prefer to use
'
for delimiting the string, so I have to escape less characters.There are people that claim to see performance differences: old mailing list thread. But I couldn't find any of them to be confirmed.
The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance when you are working with html inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.