I’m currently using a JavaScript coding style based on Douglas Crockford’s Code Conventions for the JavaScript Programming Language, which means I declare all variables used in a function at the beginning of that function:
function drawTiles(tiles) {
var x, y, tile;
for (x = 0; x < width; x++)
for (y = 0; y < weight; y++) {
tile = tiles[y][x];
if (tile)
drawTile(tile, x, y);
}
}
This makes sense because variables in JavaScript are hoisted to the top of the function and function scoped anyway.
However, I get the impression that it is more popular to just declare them when first used, like this:
function drawTiles(tiles) {
for (var x = 0; x < width; x++)
for (var y = 0; y < height; y++) {
var tile = tiles[y][x];
if (tile)
drawTile(tile, x, y);
}
}
That’s actually easier to work with IMO – you don’t have to jump to the top of the current function whenever declaring a new variable. But it doesn’t feel “right”.
My question is: Which style is more popular among professional (and popular) JavaScript programmers? (I usually try to pick the most common code style used in the community)
I had a look at a few open source projects (Google’s Closure, Facebook’s Phabricator, Facebook JS SDK and jQuery) and it seems all (except jQuery) declare variables when first used most of the time. jQuery leans towards declaring them at the top of functions, but by no means consistent.
I think the second style is popular because this is how you’d do it in most other languages, i.e. declaring the variable where it’s used.
Future versions of ECMAScript will introduce block scope through the
letkeyword, which will probably change the way people write JS (tending more towards the 2nd style).But other than that, if you keep your functions small, it really becomes a matter of taste.