I was recently exposed to a coding convention which requires you to order variable declarations in alphabetical order. Crockford mentions this in Code conventions for JavaScript. An oversight of Crockford’s, perhaps, is that he doesn’t explain why we should do these things.
So the convention requires that instead of this:
var ccc; var aaa; var bbb; |
… you do this:
var aaa; var bbb; var ccc; |
By ordering the variables alphabetically we have supposedly made it easier to find variable names.
I should probably use a real world example to demonstrate its true benefit, so here’s a chunk of variables from jQuery:
var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^.]*)?(?:.(.+))?$/, rhoverHack = /(?:^|s)hover(.S+)?b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(w*)(?:#([w-]+))?(?:.([w-]+))?$/; |
They’re using some quasi-hungarian notation which, it could be argued, negates the benefits of alphabetical ordering, so let’s remove all of the r
prefixxes so that we’ve got a good example to work with:
var formElems = /^(?:textarea|input|select)$/i, typenamespace = /^([^.]*)?(?:.(.+))?$/, hoverHack = /(?:^|s)hover(.S+)?b/, keyEvent = /^key/, mouseEvent = /^(?:mouse|contextmenu)|click/, focusMorph = /^(?:focusinfocus|focusoutblur)$/, quickIs = /^(w*)(?:#([w-]+))?(?:.([w-]+))?$/; |
Okay, now let’s re-order according to the convention:
var focusMorph = /^(?:focusinfocus|focusoutblur)$/, formElems = /^(?:textarea|input|select)$/i, hoverHack = /(?:^|s)hover(.S+)?b/, keyEvent = /^key/, mouseEvent = /^(?:mouse|contextmenu)|click/, quickIs = /^(w*)(?:#([w-]+))?(?:.([w-]+))?$/, typenamespace = /^([^.]*)?(?:.(.+))?$/; |
Did you notice the difference? The convention suggests that it is now easier for programmers to come along and find the variable focusMorph
because it is within an alphabetically sorted list. I have doubts about this though.
For me, this variable list is no easier to navigate than before. I’m probably below average in “alphabet skill” though. Sometimes I find myself reading out the alphabet internally so I can try to remember if K really does come before M. It’s sad but true.
It could very well be that this is just one of those things that only affects me. And that’s fine. I still would like to continue with my exploration of this convention though.
This convention can become a problem when, for example, one variable depends on a previous variable’s assignment. For example:
var radians = foo.getRadians(), angle = radians / Math.PI * 180, // we need radians to be defined ...; |
With the convention applied:
var angle = radians / Math.PI * 180, radians = foo.getRadians(), ...; |
But that doesn’t work anymore. When the first line runs, radians
is undefined. Of course, in this example, I could just get rid of the radians
variable and use foo.getRadians()
straight off. Yes, I could do that. But this is just an example, and I have battled with this quandary many times without such simple solutions.
So, strictly, how does one solve this, supposing it was a trickier case? Actually, wait — let’s explore why we’re solving this. Is this a programming problem? Nope, this is an issue born from tireless compliance to standards and conventions.
Is it worth fixing? Shall I? —
var angle, radians = foo.getRadians(), ...; angle = radians / Math.PI * 180; |
I fixed it! The variable declarations are in order. But at what cost? I’ve moved down the actual assignment of angle
to after the declarations.
But doing this would not serve the convention’s purpose because we haven’t made it easier to find angle = ...
.
Okay, so I guess the correct thing to do would be to rename one of the variables so that they’re ordered correctly. Now, I’m sitting here thinking of what I should name a variable. I’m looking for a word that means the same as angle
but starts with a letter beyond r
. This is starting to feel less like programming and more like a game.
Let’s be honest though. Nobody is going to have trouble finding either of these variables. There are only two. And I would argue that the jQuery variable block is also easily navigable.
As programmers, surely it is our responsibility to ensure that our code is well abstracted and that we separate our concerns. If we do this effectively we should rarely end up with lists of more than five variables in each function/method, give or take a few.
If you have a list of variables that is difficult to navigate then you’re problem isn’t going to be fixed by applying a convention — it’s going to be fixed by abstracting code and separating concerns.
Also, more often than not, the way in which I order variables is governed by the way in which they relate to each-other, semantically, and the functional story that is told through their assignments, e.g.
var data = getData(); var id = data.id; var base = getBaseById(id); // [rest of the function] // usage of `data`, `id` and `base` etc. |
A story is told through variable assignment, just like it is through flow control.
At least in my personal code I make it a policy to not let conventions have undue authority. I don’t code for conventions. I didn’t make this website so that it would pass HTML validation. I don’t worry about JSLint. I don’t lie awake at night wondering where I’ll find that lost semi-colon!
What I do worry about is creating functional and readable code. Sometimes it’s difficult and I end up with a mess. But that mess isn’t going to be fixed by stringent coding standards — it’s going to be fixed by repeated application of my programming abilities to abstract and separate.
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
I don’t see the benefit in alphabetical ordering either – as with CSS properties (I’ve read these should be declared alphabetically too) why would I want to declare padding alongside position?!
Surely the important thing to remember is when working with a team (or on code that will be edited by others at some point) then having a convention between yourselves will alleviate the pain of working with someone else’s code. All singing from the same hymn sheet!
A lot of the rest of his article does make sense (though I prefer 2 space indentations as opposed to 4!). However, as you conclude, it’s surely about programming ability rather than conventions.
I agree with you that variables should be put together section/module-wise. I don’t see any benefit of ordered declaration. What I see though is extra bit of time wasted to do so.
Alphabetically ordering doesn’t fly with me either–mostly for the reasons you’ve already outlined.
Also, maybe it’s just me, but I rarely visually search for variables. I use my IDE/text editor to find them. A good editor provides keyboard shortcuts to navigate between the currently selected word/variable and can highlight all instances of the variable. So if the key argument is it makes them easier to find, I’d disagree. Your editor should make them easy to find (and most do.)
Me four. Not seeing the point. With so many *real* style issues to be concerned with, I think this is best left to the same people who feel the need to alphabetize their bookshelves and square their stapler and tape on their desk. The effort required to maintain is more than the benefit.
Anyway I can’t help but feel that if you had so many variables that you needed to sort them to find something easily, you probably have bigger problems with the code than the order of your declarations. And of course what the previous commenter said – search.
I usually try to order things in some way that makes them readable, e.g. undeclared ones first, then simple assignments, then longer lines. This is mostly just about not have lines of dramatically different length together, which (imho) hinders readability.
If you were the last person to work on a particular code file, you will almost certainly be the person your boss assigns to work on it again when there’s a problem to be fixed.
Therefore, you should code for your own readability first and foremost. Myself, I like to define in largely alphabetical order, usually with simple values first, then calculated values (2 alphabetized lists).
But that’s me. You should suit yourself.
I run into the same problem you do when I try to alphabetize either my JavaScript or PHP variables: some variables rely on previously declared ones.
I’m a little anal about alphabetizing stuff so I still do it for CSS properties because their order doesn’t matter. But CSS is a completely different story because I have my own weird pattern for that.
An interesting post nevertheless, especially because, like you mentioned, it’s hard to find that balance between readability and functionality. Oh the problems us programmers face!
I’ve never even heard of anyone saying that you should order your variables alphabetically. My guess is that it was someone who was a bit OCD and was well known enough that when he said “order them by alpha” that everyone thought it was convention.
I also recite the alphabet aloud up to the letter I am trying to figure out.
Myself, I like to define in largely alphabetical order, usually with simple values first, then calculated values (2 alphabetized lists).