...

View Full Version : single or double quotes



andrew1234
03-06-2012, 09:11 PM
Hi

Can you please advise on this.

When writing javascript what is best practice.... single or double quotes?

I tried to research this and everyone contracdicts each other?


thanks

A

devnull69
03-06-2012, 09:28 PM
There is no such thing as a "best practice" here as single and double quotes are 100% equivalent in Javascript ... if used in pairs :-)

To avoid escaping of inner quotes you might consider using different quotes inside a string than the string delimiter quotes, but this is still up to you. Feel free to escape quotes whereever you want to :-)

All of this is equally possible


var mystring1 = "This is my string";
var mystring2 = 'This is my string';
var mystring3 = "This is my 'string'";
var mystring4 = 'This is my "string"';
var mystring5 = "This is my \"string\"";
var mystring6 = 'This is my \'string\'';
var mystring7 = "This is my \'string\'";
var mystring8 = 'This is my \"string\"';

blaze4218
03-06-2012, 10:46 PM
I like to use single quotes.
Reason: I find that within a string the " char is used far more often than the ' char, and switching to single quotes from double some years ago has greatly reduced my need for escaping \'. Also, I like to use .innerHTML to inject HTML in certain cases, and since I always use double quotes in declaring tag properties I never have to worry about mixing the two.

This decision is based entirely on my own coding practices... If you use VBScript on the same page as JavaScript, or you use VBScript as your server-side language; you might prefer to use double quotes so as not to confuse yourself with the ' that is used for single line comments in VBScript...

I think I agree that I have never heard either to be "best practice", and that you should do what makes your code easier for you to understand, and manage.

felgall
03-07-2012, 02:07 AM
Use whichever one will reduce or eliminate the number of quotes in the string that need to be escaped.

That may mean that with two adjacent assignments that you use one around the first and the other around the second.

You can even completely avoid the need to escape them by swapping mid string eg. ' " ' + " ' " is a single string containing space, double quote, space, space, single quote, space



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum