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


It is that according to me both could be used for any type 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 how you want to use the chain later.

If it must 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 who recommended you to change quotes had to refer to a case in which you contained those quotes within the string. Specifically, it is a typical advice for when you want to incorporate html whose attributes go with double quotes (or the other way around)

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

or json, which forces you to use double quotes

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

and it is also common to use, on the contrary, double quotes when strings contain text in English or in other languages ​​in which single quotes are used as 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 backtick or grave accent) ` that serve to delimit template literals but that also serve (abusing them a bit) to declare strings.

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