javascript – What is the difference between double quote and single quote? ( ' ' Y " " )


Is that according to me both could be used for any kind of thing like in strings in variables, cycles, etc. For example:

var comillasDobles = "Ejemplo";

var comillasSimples = 'Ejemplo dos';

According to me this was the same, but I have seen in many places that sometimes they say "your code is wrong because you used double quotes and they should be single" and vice versa. Could someone explain the difference to me? please.


Short answer, there is no difference.

Long answer, it depends on what you later want to use the chain for.

If it should contain double quotes, then you have to use single quotes

 var dobles = 'contiene "dobles comillas" sin problemas';

and backwards

 var simples= "contiene 'simples comillas' sin problemas";

if you have to contain both, then you have to escape with \ one of them.

 var ambas = 'contiene "dobles comillas" y \'comillas simples\' sin problemas';

Probably whoever recommended you to change the quotes must have referred to a case in which you contained those quotes inside the string. In particular, it is a typical advice for when you want to include html whose attributes go with double quotes (or vice versa)

 var html = '<a href="#">';

or json, which forces you to use double quotes

 var json = '{ "name":"value" }';

and it is also common to use double quotes instead when the strings contain text in English or in other languages ​​where single quotes are used as an apostrophe, to avoid the hassle of having to use \' all the time so it is much better to start definitions with double quotes.

  var t1 = "That's an example";

instead of

  var t2 = 'That\'s another example';

Finally, to complete the answer, in the latest version of javascript (known as ES6 or ES2015 or ECMAScript 2015 or ECMA-262 6th Edition), there are backticks (or grave accent or backtick) ` that serve to delimit template literals but which also serve (abusing them a bit) to declare strings.

 var ambas = `contiene "dobles comillas" y 'comillas simples' sin problemas`;
Scroll to Top