[Solved-5 Solutions] When to use double or single quotes in javascript - javascript tutorial



Problem:

When to use double or single quotes in javascript ?

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

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.
"Double quotes with a single ( ' ) quote in the middle"
'Single quotes with a double ( " ) quote in the middle'

Each type must have an escape in their own type:

"double quotes ( \" ) must escape a double quote"
'single quotes ( \' ) must escape a single quote'

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:

alert('Say "Hello Wikitechy"');
alert("Say 'Hello Wikitechy'");

But complicated issue get a from the below example…

alert("It's \"work\" time.");
alert('It\'s "work" time.');

Another option in ES6, are Template literals which use the back-tick character:

alert(`Use "double" and 'single' quotes in the same string`);
alert(`The escape the \` back-tick character in a string`);

Template literals offer syntax for variable interpolation, multi-line strings, and etc.

Read Also

Java Characters

Solution 3:

The difference is demonstrated in the following code:

'A string that\'s single quoted'

"A string that's double quoted"

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.

<a onclick="alert('hi');">hi</a>

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 :

var foo = '<div class="wikitechy-website">wikitechy</div>';

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:

//JSON Objects:
var jsonObject = '{"wiki":"techy"}';
//HTML attributes:
document.getElementById("wikitechy").innerHTML = '<input type="text">';

Then, we prefer to use ' for delimiting the string, so we have to escape less characters.



Related Searches to javascript tutorial - When to use double or single quotes in javascript