Single quotes vs. double quotes
I’ve written about this before. Unfortunately I’ve gone back and forth on whether I should keep a blog or not, so I have to write it again.
So: double quotes (“) and single quotes (‘). In programming, they’re used to state that something is a string of text (e.g. “This is a string of text”, or ‘This is a string of text’). So even though we use them for the same reason most of the time, there are some some times when you must use one or the other. Escaping
One of the circumstances is if your sentence contains a double quote or single quote. For example, if the text I wanted to display is: I’ve had a great day today. I can’t use the single quote string because otherwise the single quote in the text would end the string (i.e. ‘I’ve had a great day today’). The same goes for double quotes. You end up having to escape the quote characters if they’re used:
quote = "Michael Jordan: \"I've failed over and over again in my life... and that is why I succeed\""
quote = 'Michael Jordan: I\'ve failed over and over again in my life... and that is why I succeed'
Interpolation
Another reason to use one of the other is when you need to interpolate (embed) one string in another. A lot of programming languages have this feature, but I’m going to use Ruby as an example.
In order to interpolate a string in Ruby, it must be a double quoted string. That’s just how it is. So I’m able to do the following:
name = 'Daniel'
puts "Hello #{name}"
puts 'Hello #{name}' # does not work
My strong opinion
So there are the two primary circumstances when you have about when to use a single quote or a double quote. Does the string you’re writing have a single quote or double quote in it? Better use the other one so that you don’t need to escape. Do you need to interpolate another variable into your string? Better use double quotes. Hang on, that single quote string has changed so that it now needs to interpolate: better change it to double quotes.
My main problem with this is that there is too much thinking around when to use single quotes vs double quotes. So here it is: just use double quotes. Everywhere. I don’t even want to have to think about it. The less decisions that I have to make the more focussed I can be on what matters.
There are definitely performance benefits to use single quotes, but that usually isn’t a concern in most of the work I end up doing. I want to spend all my time and energy thinking about the complex product problems that I’m solving. Not whether I need to use a single quote or double quote.
It’s a little OCD, but I’ve spoken to a few people about this and they tend to agree. Even though I’m sure it’s just to get me to move on to another topic.