Philip Walton
Philip Walton

Reputation: 30451

Are there downsides to using var more than once on the same variable in JavaScript

Before asking my question, let me give a disclaimer. I know what var does, I know about block scope, and I know about variable hoisting. I'm not looking for answers on those topics.

I'm simply wondering if there is a functional, memory, or performance cost to using a variable declaration on the same variable more than once within a function.

Here is an example:

function foo() {
  var i = 0;
  while (i++ < 10) {
    var j = i * i;
  }
}

The previous could just have easily been written with the j variabled declared at the top:

function foo() {
  var i = 0, j;
  while (i++ < 10) {
    j = i * i;
  }
}

I'm wondering if there is any actual difference between these two methods. In other words, does the var keyword do anything other than establish scope?

Reasons I've heard to prefer the second method:

  1. The first method gives the appearance of block scope when it's actually function scoped.
  2. Variable declarations are hoisted to the top of the scope, so that's where they should be defined.

I consider these reasons to be good but primarily stylistic. Are there other reasons that have more to do with functionality, memory allocation, performance, etc.?

Upvotes: 12

Views: 885

Answers (5)

Peter Olson
Peter Olson

Reputation: 142939

There will not be any differences during execution time. There might be a imperceptibly small difference in interpretation/compilation time, but that of course will be implementation dependent. There also might be a few bytes different in the size of the file, which could also affect download time. I don't think either of these are worth being bothered about.

As you already know, any variable declaration will be hoisted to the top of the function. The important thing to note is that this occurs during the interpretation/compilation process, not during execution.

Before a function is executed, the function must be parsed. After each function is parsed, they will both have all of the variable declarations moved to the top, which means that they will be identical and there will be no execution time cost incurred.

For the same reason, there are no memory cost differences. After parsing, there will be no differences at all.


Since you are not asking about style I am not telling you which I think is better. But I will say that the only reason you should prefer one over the other is style.

Upvotes: 3

user166390
user166390

Reputation:

Style

Subjective. I prefer the approach that keeps the var close to the usage site, but I always keep the scoping rules in mind. I also avoid combining multiple declarations into a single var and prefer multiple var statements.

Memory allocations

Variables are not objects: not applicable. Due to the hoisting rules, the variable "slot" has the same lifetime in all cases.

Performance

No. There should be no difference in terms of performance. While an implementation could technically really mess this up - they don't.

The only way to answer this (besides looking at every implementation in minutia) is to use a benchmark.

Result: noise differences on modern browsers

Upvotes: 3

Jivings
Jivings

Reputation: 23250

In JavaScript - The Good Parts Douglas Crockford suggests that by using the second method and declaring your variables at the top of their scope you will more easily avoid scope bugs.

These are often caused by for loops, and can be extremely difficult to track down, as no errors will be raised. For example;

function() {
  for ( var i = 0; i < 10; i++ ) {
    // do something 10 times
    for ( var i = 0; i < 5; i++ ) {
      // do something 5 times
    }
  }
}

When the variables are hoisted we end up with only one i. And thus the second loop overwrites the value, giving us an endless loop.

You can also get some bizarre results when dealing with function hoisting. Take this example:

(function() {
  var condition = true;
  if(condition) {
    function f() { console.log('A'); };
  } else {
    function f() { console.log('B'); };
  }
  f(); // will print 'B'
})();

This is because function bodies are hoisted and the second function overwrites the first.

Because searching for bugs like this is hard and regardless of any performance issues (I rarely care about a couple of microseconds), I always declare my variables at the top of the scope.

Upvotes: 5

Spencer Lockhart
Spencer Lockhart

Reputation: 1174

Your example will function exactly the same. It could be even more unclear than your example to use 'var' in a block, though. Say, for example you want to update a variable that is outside of the scope (by not using 'var') conditionally, or use a local 'var' instead. Even if that condition is false, 'j' becomes local. It turns out not to be as trivial as it appears to do that.

var j = 1;
function foo () {
    j = 2;
    if (false) {
        var j = 3; // makes `j = 2` local simply for being in the same function
    }
    console.log(j);
}
foo(); // outputs 2
console.log(j); // outputs 1

That's one tricky case that may not work as you expect just by looking at the code.

There are no downsides to declaring every 'var' on top, only up-sides.

Upvotes: 0

MrPurpleStreak
MrPurpleStreak

Reputation: 1557

The 2nd way saves the 4 characters in the the javascript file - but in terms of the actual code generation or execution speed I don't believe there is any difference at all.

Upvotes: 0

Related Questions