[Solved-5 Solutions] When to use double or single quotes in javascript - javascript tutorial
Problem:
When to use double or single quotes in javascript ?
Solution 1:
- There is no difference between using single or double quotes, meaning they both represent a string in the end. The other character within a string no need to escape.
- While in a double quoted string can have single quotes without escaping.
- In the single quoted string can have double quotes within it without having to escape.
Each type must have an escape in their own type:
Solution 2:
The possible reason to be used for single vs double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suitable for the string:
Using the other type of quote as a literal:
But complicated issue get a from the below example…
Another option in ES6, are Template literals which use the back-tick character:
Template literals offer syntax for variable interpolation, multi-line strings, and etc.
Solution 3:
The difference is demonstrated in the following code:
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.
Solution 4:
Inline JavaScript single quotes are our only option for string literals.
But we can't wrap the "hi" in double quotes, via any escaping method. Even "
which would have been best guess (since the escaping quotes in an attribute value of HTML) doesn't work in Firefox. \" won't work either because at this point we escaping for HTML, not JavaScript.
Solution 5:
When we handle HTML into JavaScript, it's easier to use single quote while compared to double quote :
And at least JSON is using double quotes to reprensent strings.
Solution 6:
If we can use ' for delimiting a string, we will need to escape " quotes. We are always prefers to use " quotes inside the string, for example:
Then, we prefer to use ' for delimiting the string, so we have to escape less characters.