I am currently using the JavaScript coding style based on Douglas Crockford's "Code Conventions for the JavaScript Programming Language" , which means that I declare all the variables used in the function at the beginning of this 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 go up the top of the function and functions anyway.
However, I get the impression that it is more popular to simply declare them on first use, for example:
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); } }
Itβs actually easier to work with IMO - you donβt have to jump to the top of the current function when declaring a new variable. But that does not seem to be "right."
My question is: which style is more popular among professional (and popular) JavaScript programmers? (Usually I try to choose the most common code style used in the community)
I have looked at several open source projects (Google Closure , Facebook Phabricator , Facebook JS SDK and jQuery ), and it seems that everyone (except jQuery) declares variables at first use most of the time. jQuery tends to declare them at the top of functions, but by no means consistent.
source share