Should var commands be the first in JavaScript functions?

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.

+4
source share
1 answer

I think the second style is popular because you do this in most other languages, i.e. declare the variable in which it was used.

Future versions of ECMAScript will introduce a block area using the let keyword, which is likely to change the way JS is written (more suited to the second style).

But other than that, if you keep your functions small, it really becomes a matter of taste.

+1
source

All Articles