Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with:

People! Please Stop Using Single Quotes!

By Ben Nadel on
Tags: ColdFusion

On my journey to ColdFusion mastery I look through a LOT of code. One thing that irks me to no end is the hugely prevalent use of singles quotes:

  • <cfset url = 'http://localhost/ilove/single/quotes/' />

I see this and it drives me bonkers! These people must not code inside of an IDE that has color coding (are you still coding in Notepad?). Most IDEs that I have used don't have special default color coding for single quotes. For double quotes, on the other hand, they do (usually a nice, easy to read blue). It makes reading the code soooo much easier.

So, are you trying to make your code hard to read (I can respect that, after all, your code, your rules)? I thought maybe it had to do with "old school" programming... but if memory serves me correctly, aren't single quotes used for characters and double quotes used for strings?

Someone please end the madness. Can someone give me a single good reason (other than personal preference) why single quotes should be used around strings and attributes?

Tweet This Titillating read by @BenNadel - People! Please Stop Using Single Quotes! Thanks my man — you rock the party that rocks the body!



Reader Comments

Dreamweaver color-codes single- or double-quotes. So does Eclipse if memory serves.

Can't use double-quotes in SQL queries. If I recall, single-quotes are also preferred in JavaScript. I've never programmed in C, but I think single-quotes are preferred there, too.

That said I prefer double-quotes. They're easier to see, I think.

Reply to this Comment

Al,

I haven't used Dreamweaver (I still use Homesite) and I don't recall for Eclipse. I can tell you, however, from years of experience that Javascript has no sense of good or bad for single quotes. In fact, if I had to say anything, I would say it's better to use double quotes in Javascript so you don't have to escape single quotes within strings:

var strTest = 'Single quotes! They\'s bunk!';

vs.

var strTest = "Single quotes! They's bunk!";

Notice that I don't have to use any unnatural looking escaped characters for often used single quotes. More often than not, I find, you need to use nested single quotes than nested double quotes.

Reply to this Comment

Ben, I also HATE the use of single quotes in attributes. I can only think of one time that I use them. If I'm trying to produce a line of HTML output, say:

<a href="http://www.cnn.com">CNN</a>

If I were creating that whole string inside a cfset, I might wrap it with single quotes, so that I didn't have to escape the double-quotes.

Other than that, I can't think of a reason you shouldn't be whipped with a wet noodle for using them.... ;-)

Reply to this Comment

Got to go with Demian on that one! Its the only time I've used single quotes over double quotes. The thing is I have known some developers who loved using single quotes all the time. In fact one of them I work with. I only remember asking once to a developer last year why he used single quotes all the time. Only response I got was that he found it much easier to read his code or others.

Reply to this Comment

Yeah, I guess it all comes down to personal preference. I personally find single quotes harder to read. They seem too "inline" to me. Double quotes give my eye more of a visual break as if to say "Yo dude, I am about to start or end an important value."

Reply to this Comment

Eclipse certainly colour-codes single-quoted strings. What other IDE for CF is there? ;-)

I find it's horses for courses. If I need to embed a double-quote in a string, I'll wrap it in single quotes (preferring this to escaping the double-quote). Other than that, I err towards double-quotes for strings.

In the bigger scheme of things when it comes to maintaining other people's code... it's not really one of the major issues, I think.

--
Adam

Reply to this Comment

wft is wrong with you? wtf cares? post something useful. You're on goog - dont abuse the privilege with bs rants like this.

Reply to this Comment

Mike,

I have been told over my life that there is Plenty wrong with me.

But seriously dude, don't get all steamed. I try to keep my rants to a minimum and I try to keep the majority of my posts highly relevant and chock-full-o-code. However, I understand that my stylings are not for everyone. It's not personal. If you feel that my contribution to "Goog" is not useful, by all means request that I be removed. I will not take offense.

Reply to this Comment

Hey Ben, good work on your blog always good stuff here, forget that other wombats comments. I normally use double quotes just as a personal preference but came across the first occurrence today where I had to reverse this it was using

<cfheader name="Content-Disposition" value='attachment;filename="download a document Description.pdf"'>

I understood that I had to escape the spaces in the filename, however this would not work if I had double quotes around the value, this was using firefox to download. First time I came across this though.

Reply to this Comment

You obviously havn't done much coding.

After a while you will find many places where you need to resort to single quotes, and it eventually makes sense to do this evey where.

A simple example, ohh lets say putting any function in a HTML element.

<a href="#getUrl('home')#">#getTitle('home')#</a>

Reply to this Comment

Ooops! I just posted my comment to "Ask Ben". Sorry.
Fortunately FF kept the content, so I can re-post to the correct place:

For attributes (both HTML or CFML), I always use double quotes, even if it means escaping inner doubles.
For structures I always use single quotes.
For functions, I'll use single quotes if its a 'simple' variable - ie: empty or a one-word string.
If its a long string, or a cfset-ed string, I go for double (unless it would involve escaping, in which case I'll resort to single).

See, perfectly logical! :>

Reply to this Comment

Dale,

I understand what you have done the problem with my example is it only works if you escape everything with single quotes as soon as you try double quotes on the outside and single on the inside it no longer works.

Reply to this Comment

When you get into a lot of OO cfc stuff, you need single quotes more and more.

For example in our app every string goes through a translation macro. For language translations. So every string needs to have a function around it.

<h1>#tr('Heading')#</h1>
<p>#tr('The quick brown fox')#</p>
<a href="home.cfm">#tr('click here')#</a>
<img src="logo.gif" alt="#tr('Company Logo')#" />

Reply to this Comment

@Peter B.

I am glad that you have a methodology. That's cool man.

@Dale,

I assure that I have done many years of programming (though not as many as I would like). As for your examples, mixing CFML inside of HTML is moot point as they are both parsed at different times and in different places. Having double-quotes in a CFML call inside an HTML attribute has no side effects at all (except that the IDE is probably going to have some trouble with color coding):

<a href="#UrlEncodedFormat( "sweeet.htm" )#"></a>

In this case the double quotes in the method argument do not interact with the double quotes of the HREF attribute in any way.

I am not sure what OOP and string translation has to do with double quotes?

Reply to this Comment

Single quotes are the lazy man's double quotes.
You don't have to press the shift key to type a single.
And yes, there is something wrong with that.

Reply to this Comment

I just thought I'd point out how funny it is that a commenter on here named Mike complained about what he considered a useless blog post that happens to plague Goog. Personally, I've never used Goog so I guess I'm very biased when I say who cares but the point is after reading several of your blog posts for the past 2-3 months this definitely has to be the one with the most comments. Funny how sometimes the most simple or awkward, or even useless blog post can be the one most commented on. Goes to show what some people know!

Reply to this Comment

For Mike, the goog complainer, this is way less off topic than most posts. One of the great things about goog and other aggregators is you get the title and a sentence or two. Skim and either drill down or skip. Don't go everywhere and complain.

To get back on topic, Ben, personally I like single quotes when passing parameters to a function or referring to a structure key, but I agree that double quotes should be used for attributes, setting variables, etc.

I don't have a good reason for this, just my preference. However, if faced with working on a project where others are doing it differently, I can adjust to be consistent.

Reply to this Comment

Hey no problem man. Us CF developers got to look out for one another. You share your hard work and code with us and I do my best to share my support. The Family provides quality protection. Fogehaboutit! :)

Reply to this Comment

I use single quotes exclusively, because it is far easier to integrate into the PHP code my programmer buddy writes. He prefers double quotes, so it is a matter of making his life easier.

DW and Aptana/Eclipse color-code single quotes, but DW doesn't let one autocomplete with single quotes which is why I don't use DW.

Reply to this Comment

most single quotes are from dynamic pages that has php spit out the content....its easier to use single quotes...

about 50/50 ill escape the double quotes versus the single '

\" is just more work...

Reply to this Comment

Putting text in double quotes adds an extra step for the processing engine: the string is read in, and then re-interpreted to parse out any special characters, variables within, etc. Whereas a single-quoted string is just read in and that's it.

So, if you're taking performance optimization into account, you should use single quotes for setting text strings, if you want to save some processing overhead. How much overhead can you save? Probably negligible on a small-scale site, but as a site gets larger / more traffic, it can be significant.

In any case, it's always better to escape out of strings when adding variables, i.e.

<cfset out = 'this variable is: ' & variables.rockin & ', right?'>

it's also best to avoid using the ## syntax as much as possible

Reply to this Comment

@Chip,

I am not sure whether avoiding the ## in strings actually will save you any overhead. ColdFusion still has parse each string looking for uses of #variable#, so I don't think you are going to save much. Plus, I would hope that the ColdFusion compiler would be smart enough to, behind the scenes, replace ## string variables with something that is optimized.

Reply to this Comment

I like double quotes better. It feels more.... whatever it feels, it feels more of it using double quotes. No reason.

That said, single and double quotes are processed differently in several languages such as php; single quotes enclose a string; you can put a variable in it (for instance: 'here is a $variable to use') and it will be passed as a string. If you enclose that same string in double quotes, php will try to process the $variable. A quick and easy shortcut if you don't want to write "here is a " . $variable . " to use".

Reply to this Comment

You know what grinds my gears? Working on someone's code when they've used the literal single quote characters in a replace function. It screws up the syntax highlighting in Eclipse for the rest of the file.
#Replace(myString,"'","''","all")#

I end up changing it to
#Replace(myString,chr(39),"#chr(39)##chr(39)#","all")#

Just my personal preference... Keeps my code clean and readable.

Reply to this Comment

If the html is produced by a server-side script, single quotes can be easier to code, the compiler will ignore special characters in single quotes, but not double quotes.

For example (php):

$url = "http://bennadel.com";

echo "<a href='$url'>Click here</a>"; // Creates a link to bennadel.com
echo '<a href="$url">Click here</a>"; // Creates a link to $url

Not to mention some people just get into the habit of using single quotes from writing lots of SQL.

You can probably change a setting in whatever you're using to write html, I use eclipse and it changes the color of both single and double quotes.

Reply to this Comment

An important difference:
In a cfquery, single-quoted strings get escaped, even without cfqueryparam. Double-quoted strings get passed right through. So if you're preventing SQL injection the lazy way, single-quotes will help but double quotes won't.

Reply to this Comment

I prefer single-quotes in PHP and JavaScript.
Double-quotes are required in XHTML attributes which makes it not a matter of preference but syntax.

In PHP double-quotes are subject to string interpolation which expands \t, \n, \r, etc. and variables. Using single-quotes avoids PHP to do this, usually, unecessary interpolation.

Reply to this Comment

@Thomas,

Coming from ColdFusion, I had never seen that before. But, now that I am playing around with Groovy, I see similar functionality - double quotes are evaluated, single quotes are not. This definitely changes the game.... IF you work with a language that differentiates.

Reply to this Comment

The argument for not having to escape doesn't really hold water, nested quotes happen in both directions.

consider:
I've always used "Hello, World!" as an example.

Just to note, the same is true of Perl as in PHP, double quoted strings are interpolated. So single quotes are the norm for string literals to avoid the expression engine invocation as well as parsing for nested variables.

Also, what editor are you using that you can't fix this code-coloring with a simple style tweak? Maybe the fix is to get a more robust editor? :P

Reply to this Comment

@Thomasb,

My editor is definitely a bit old. It has color coding, but I don't think it has quote-type color coding.

Reply to this Comment

"Can someone give me a single good reason (other than personal preference) why single quotes should be used around strings and attributes?"

Hello,

I found a spot where single quotes are necessary around strings: when passing json strings that contain quoted elements during an AJAX request using ColdFusion.

I stumbled on this when I tried to pass the following json string back to javascript:

<cfset json = '{"results":"Here is a "quoted string" i am sending."}'>

Only, in ColdFusion, the quotes surrounding "quoted string" need to be escaped. So I got:

<cfset json = '{"results":"Here is a ""quoted string"" i am sending."}'>

However, the string, when sent to output:

<cfscript>
WriteOutput(json);
</cfscript>

Looks like this is firebug's Net > Response tab:

{"results":"Here is a ""quoted string"" i am sending."}

Which JavaScript won't eval properly.

So, the solution is to concatenate a bunch of strings together and begin the strings with a single if you need an inner double, or begin with a double if you need an inner single:

<cfset json = '{"results":' & "'Here is a" & '"quoted string"' & " i am sending.'" & "}" />

Which is sent to JavaScript, and eval'd correctly, as:

{"results":'Here is a "quoted string" i am sending.'}

Note I am enclosing the name part of the name/value pair in this object in quotes for compatibility with Internet Explorer.

Reply to this Comment

@John,

While you typically do have to escape your qoutes in ColdFusion by doubling up on them, since your original JSON value was wrapped in single-quotes, you actually don't need to escape the double ones; this is why it was coming through unespaced in the AJAX. Your first approach:

<cfset json = '{"results":"Here is a "quoted string" i am sending."}'>

... was fine at the ColdFusion level since the single-quotes are the "containing" delimiter. However, this will break in the Javascript layer because at that point, the Javascript string value:

"Here is a "quoted string" i am sending."

... has unescaped quotes. In Javascript, however, the method of escaping is different. Special characters are escaped with back-slashes:

"Here is a \"quoted string\" i am sending."

Putting these two together, your can use the string:

<cfset json = '{"results":"Here is a \"quoted string\" i am sending."}'>

This stuff is definitely crazy and you have to think at multiple levels. All I have to say it, thank goodness that CF8 gave use serializeJSON() and deserialiseJSON() functions!

Reply to this Comment

Do you still feel the same way about single quoting? I prefer it because you don't have to hit the shift button to get them like you do with double quotes.

Plus it's easier to tell what type of quote it is when working with smaller point size editors.

Reply to this Comment

Now when Andy and John raised this topic from dead , I must say a word about this :)))

After reading all comments here and (re)evaluating my opinion about it, I must say: It is all about a personal preference, that is "De gustibus non est disputandum".

For many year I used double quotes for strings and it came from C where double quotes surrounds strings and single chars. But, when my last client imposed opposite rule by their coding guidelines I found quite easy to adopt to it, and now, even I am not working for that client, I continue using it.

(kid woke up, must leave :))

Reply to this Comment

@Andy,

I am still a big double-quote fan. Of course, I am also a big white space fan. I think to me, part of the double-quote issue is that it simply makes a LARGE delimiter in my code that I can visually parse faster.

Plus, since I am still in HomeSite, single quote are not color coded in the same way.

At the end of the day, people just need to be consistent. There's nothing that frustrates me more than irrational coding standards. People throwing double quotes here and single quotes there (in a language where there is no processing difference)... totally unacceptable :)

@Marko,

Yeah, I think it's just personal preference.

Reply to this Comment

"At the end of the day, people just need to be consistent. There's nothing that frustrates me more than irrational coding standards. People throwing double quotes here and single quotes there (in a language where there is no processing difference)... totally unacceptable :)"

This is exactly the right argument to make. It's not so much important what convention you use, the most important stylistic aspect of any convention is consistency and easy to follow rules of thumb.

Perl has several different types of ways to quote a string, qw/blah/, "blah", 'blah', q(), qq() all of which apply in different situations. In something like PHP you have '' and ""; those mean different things. '' means literally that string; "" is in fact parsed.

<?

$i = 1;
echo '$i\n';
echo "$i\n";

?>

That would yield this:eaheah

zach@isaho:~$ php quote_test.php
$i\n1

Although, if I were using cold fusion (which you're talking about) I'd probably stick to "" everywhere because it resembles markup. My preference in markup languages is for strictly double quotes.

"So, the solution is to concatenate a bunch of strings together and begin the strings with a single if you need an inner double, or begin with a double if you need an inner single:"

I'd just avoid too much concatenation, it can make your code a lot more difficult to read than something like a sprintf().

Reply to this Comment

I agree with several other people. I use single quotes because everything I write has to do with with the web. So very very often in defining variables or passing strings of any kind HTML is included.

It seems far less work to me to use single quotes ALL the time than to escape double quotes as frequently as I need to. I hate escaping within a string unless it's absolutely necessary because I think it's ugly. And, worse, I see a lot of programmers do this (in their language of choice from CF to JS to PHP):

blah = "[a href='http://www.example.com']example.com[/a]";
(replacing [ and ] with < and >)

And NOTHING is going to piss me off more than that. Too few developers have proper respect for HTML. Sure, it works and evidently in XHTML there's no real problem with it, but standards aren't just what specs say, they are what most people do. HTML attributes should always be quoted for consistency and double quoted to match the most common practice. *mutter*

You might say the same about strings in programming, but I care more about HTML and readability. Single quotes enhance readability for me because I've never used an IDE or any application with syntax highlighting that had a problem with them.

I try to be consistent and use single quotes always. I like that it allows me to so easily distinguish between array keys and strings, too, because I use double quotes in array keys.

I'd argue your IDE has an issue...it's a valid string start/end in every language I've ever used.

Reply to this Comment

@Zach,

Word up, consistency is key. And, in all fairness, I do work in a language that does not differentiate between types of strings. I'm gonna try playing with some other languages to see how they work.

@Rhy,

While we differ on which to use, we both definitely agree on consistency! And that's alllright in my book :)

Reply to this Comment

use single quotes for the speed improvement in skipping interpolation.

upgrade your IDE if it is preventing you from being able to read code according to your preference. that is probably another matter altogether.

single quotes are easier to type and allow you to reserve double quotes for literals.

when writing code that will be used in community projects like Drupal and jQuery, there are instances where single quotes is the convention.

Reply to this Comment

@Brian,

My latest IDE now correctly color-codes single quotes; but, I guess I've been using double-quotes for so long that I just find single quotes to be unattractive. I know it sounds crazy to assign attractiveness to types of quotes, but that's just how my mind is wired :)

As far as speed improvements, I have not actualy programmed (professionally) in a language that differentiates between double and single quotes as far as functionality goes. My server-side language is ColdFusion and my client-side language is Javascript - neither of which care.

Reply to this Comment

I find I often program double quotes in HTML and CFM documents and single quotes in javascript. The only real reason I do it is I will often layout a block of dynamic html to view it, then simply cut and paste it into the javascript block, ad single quotes and + where needed.

Dreamweaver CS4 does not have HTML hinting within javascript. Also I found over the years that when inside a cfquery using double quotes to enter strings saves error messages when someone punches in a single quote in a textarea or text box.

Reply to this Comment

@Mike,

Coming from a ColdFusion background, I was not used to languages having different meanings for different quotes. In fact, the only thing that I had known before that was in older languages where CHAR data types could only be defined using single-quotes - a requirement that seemed simply absurd in a strongly typed language.

I now know that some languages really do put different features in place depending on the string type. And that makes sense... so long as that is the driving force behind decision making.

@Ernest,

Yeah, I've definitely run into SQL problems with quotes :) The one that I CANNOT stand is that escaping special keywords in MySQL requires the tick (the single quote's unattractive cousin) :P

Reply to this Comment

@Ben,

I can see what you're saying about readability, but at the same time, I love coding using notepad. I'll admit, I do like dreamweaver/etc., and enjoy using them, but sometimes, I just really like to use notepad to code. I'm not kidding, really. I know I'm odd...

Reply to this Comment

How about this for a good reason, when incorporating the HTML in to a server side language such as PHP it means that if you use single quotes in the HTML, you can use double quotes in the PHP easily. In my opinion double quotes in PHP are far superior as it allows the use of variables to be included at greater ease, for example using single quotes could read

  • echo 'Hello '.$name.'!';

but with double quotes it is simply

  • echo "Hello $name!";

Reply to this Comment

@Richard

Your statement is of course true, it makes it *easier* to include variables. However, there is a performance overhead in doingg that, albeit maybe not noticable on regular applications like a WordPress blog or whatever.

Furthermore, imagine you have to process this variable in some way, adding a strtolower() around it surely breaks your 'neat n superior' double-quoted string, so why not keep string constants and variables seperated in the first place? :)

I use single quotes for everything besides HTML in a string or SQL queries, since I cannot stand single-quotes in HTML attributes :D

Reply to this Comment

@Victor,

My IDE these days does allow for properly color-coded single quotes. That said, I still prefer to use double-quotes. Of course, I'm also working in a language that makes no difference between quote type.

Reply to this Comment

in PHP double quotes strings are parsed and PHO is looking for $vars, if it find it change to value of $var with single quotes it doesn't do that. So that is an efficiency issue, and if you only send a text to user you HAVE to use single quotes

Reply to this Comment

So your only basis for desiring single quotes is because of a shortcoming in your IDE?

Wow, if only every style guide was driven by such useful needs.

Reply to this Comment

@Percy,

Clearly, I was a more naive person 6 years ago. I didn't have much IDE experience to know that different IDEs were that different.

I was recently reading a book by Nicholas Zakas and he made an interesting point - he uses double quotes because he finds that more consistent across the languages he writes. So, for example, he writes a lot of Java, which treats double quotes as strings and single quotes as characters. He finds it easier to just go with double-quotes, then, since it keeps it consistent.

At the end of the day, I tend to enjoy consistency.

Reply to this Comment

Funny this came back up. This is one area that I have not made my own standardization on yet. As I am learning more languages, yes double quotes is more standard, and considering CF is on top of Java, your case is even more relevant and that's what I've been telling myself. The problem is that double quotes cost a modifier key. :( If they only had their own button, I'd fully embrace them.

I am just glad we CAN use both in CF becomes sometimes it is nice to do quick string concatenation that may contain single or double quotes. We can just wrap it in the other and we're ok. Probably not best practice, but it is a lot easier when you just need to get it done.

Reply to this Comment

I have really enjoyed this horrible problem.

I have written a mod_perl application, that queries and inserts into PostgreSQL databases, also produces javascript on the fly to go into xhtml code.

To make it all perfect, both ' and " are also legitimate values as feet and inches. So they must both display and produce usable values upon submitting forms that either search a drop list of existing vaules or insert/update existing values with text form fields

Reply to this Comment

Okay, so double quotes appear to be the way to go in most instances, except for single characters. But which type should I use for empty strings?

  • document.getElementById("foo").innerHTML = "";

or

  • document.getElementById("foo").innerHTML = '';

(I'm guessing the former but I'd still like your feedback.)

Reply to this Comment

Hi Ben

It's hard to come up with the right answer here. I think it has a lot to do with personal preference. For me at least I see the problem as following:

Assuming that JavaScript is the behavior control center of the Web Technologies and assuming that the standard quotation in the information and appearance formats (HTML, JSON, CSS) is to use double quotes, I simply prefer to use Single quotes in the behavior as I might need to modify and/or process a lot of the information and therefore would need to escape my double quotes.

i.e. if I'm using a bad pattern and modify my innerHTML manually I can do:
document.querySelector('body').innerHTML = '<div class="test"></div>';
Rather than:
document.querySelector("body").innerHTML = "<div class=\"test\"></div>";

...or I'm preparing some JSON manually, which honestly I can't justify right away why to do:
var json = '{"a": 10, "b": "test", "c": ["test", "test2", "test3"]}';
Rather than:
var json = "{\"a\": 10, \"b\": \"test\", \"c\": [\"test\", \"test2\", \"test3\"]}";

This sort of modification is for me more likely than the usage of text information in my JavaScript that includes single quotes and that's the reason why I personally like to stick to single quotes in JavaScript but double quotes in CSS, HTML and JSON.

Reply to this Comment

Post A Comment

?
You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.