yajhsq
Last Updated: February 25, 2016
·
788
· ultimatedelman
0e2e822d32a7ab3d7f0b7098d03b1d16

Stop It With the Vars

If there's one thing that is a greater sign of laziness (or incompetence (or ignorance)) in Javascript, it is the constant declaration of variables in functions. What I mean is this:

function terribleFunc() { 
     var x = 0;
     var y = 1;

     for (var i = 0; i < 10; i++) {
         var num = x + i;
         var total  = num + y * x;
         y *= i;
     }

     var data = {
         prop1: x
         , prop2: y
     }

     return data;
}

Don't worry about what the function does, I'm sure it actually does nothing. I see this all the time in demo code or repo code for plugins or libraries around the web. The point is, you don't ever need more than one var statement in any function scope. Rewritten, terribleFunc() should look something like this (again, don't worry about what it does, focus on the structure):

function terribleFunc() { 
     var x = 0 //variables with value declarations
         , y = 1
         , i, num, total, data //variables without value declarations
     ;

     for (i = 0; i < 10; i++) {
         num = x + i;
         total  = num + y * x;
         y *= i;
     }

     data = {
         prop1: x
         , prop2: y
     }

     return data;
}

Notice how I pulled all the variables out and to the top of the function. If you've read the revered "Code Complete" you know that it says that you should declare variables as close as you can to their usage. This is absolutely correct... for all languages except Javascript. Because of hoisting, the Javascript interpreter restructures your code like the second example anyways, so it's better to have everything how it will be at runtime so you know exactly what's going on in your code.

One thing novice Javascript programmers err on is thinking that loop control structures (for, while, etc.) have variable scope; they do not. If you declare a variable inside a loop, it gets hoisted out at runtime, meaning you could have some issues with your variable values.

Also notice how I declared all of my variables using one var statement. While you may not agree with my comma-first notation, the overall structure is much cleaner, as multiple var statements are not only unnecessary but they add more bytes to what gets sent over the wire on download. The latter may not seem like a big deal for small projects, but if you're using a var declaration for every variable declaration in a big file, those bytes add up.

tl;dr

When declaring a variable in a Javascript function, put it in a list with one var declaration at the top to avoid errors and to keep your function clean.

8 Responses
Add your response

13578
0 rm zu mj7jof6znkrw3quhu9suuaxjkkm26euhhqty70rmpxbegjg8ye zrrbv5evsri bnozmkd

I think there is no benifits of doing that , declaring the varibale in usage make it easy to read and navigate.
Also when you debug the code , you will know when its exacly declared (why should I declare it before use it ??)

over 1 year ago ·
13579
0e2e822d32a7ab3d7f0b7098d03b1d16

The biggest reason why, as explained above, is due to hoisting. When you declare a variable in the middle of your function, it's not actually getting declared there at runtime. This can lead to all sorts of errors, especially if you're declaring the value of said variable to be a function. I recommend you read the hoisting article mentioned above, namely this part.

over 1 year ago ·
13599
E2b29ef458f37fd509a7ee698424a9c5 normal

I agree about declaring variables at the beginning of the function, but not about "saving up some bytes and making the code look uglier", that's just premature optimization and unnecessary if you're minimizing your code later (Concat+UglifyJS+gzip). I'll only recommend this if you're working on a project of your own, but for other developers it might be harder to read.

Also, Crockford.

over 1 year ago ·
13601
0e2e822d32a7ab3d7f0b7098d03b1d16

I didn't say making the code look uglier, you did :) I think it looks way cleaner to know where my vars are and that they're being initialized in the order I want them to. The saving bytes part is just a side effect, but the main issue is preventing hard-to-debug errors due to hoisting.

over 1 year ago ·
13680
0 goniworhrdizozyquf6pwgf5 inze1mqumcywgyqda8xvbm6m2qfljhvp5qidq7eidnjkvahsbu

I agree with the author in that you avoid a lot of potential hoisting errors and your code generally looks cleaner. Additionally if your team consistently declares at the top you always know where to look for the declarations instead of having to search the code. To nitpick from a performance standpoint it is however more performant to use var for each declaration based on my latest tests (4ms to 8ms over 10m loops - Firefox). I personally using one var statement/comma delimited though because it reads cleaner.

over 1 year ago ·
13697
B8f8f573e852c25d5750027fdb5ca38f

I love the simplicty with which CoffeeScript takes care of that for me

over 1 year ago ·
13698
0e2e822d32a7ab3d7f0b7098d03b1d16

haha... don't even get me started on coffeescript... ugh

over 1 year ago ·
13749
Avatar

There's too much distance between the declaration of the variable and the actual use of the variable. It isn't painful in a very simple example but will end up being a mess of header declarations that have no clear association with their actual use. This will make maintaining of the code more difficult because the variable's intent will eventually drift and become obscured over time. It will also make refactoring much more difficult because code is splattered across the file making extraction an undesirable challenge.

over 1 year ago ·