The WebApp Wizard Web development made magical

14Dec/108

Javascript variable declaration and hoisting

Do you know what JS hoisting is? If you do, I guess you already declare your variables properly. But if you don't, I am pretty sure you can still improve your code a little bit, and make it much more reliable.

If you already experienced some strange variable behavior, like a variable's value being unexpectedly changed or not changed, this post is for you.

Let's see how JS handles variables through a few examples.

JavaScript variables scoping

First, let's have a look at how JS variables are scoped. One may think that JS is a C-like language. And yes, the syntax is quite C-ish. But the language works quite differently. And yes, variable scoping is really different from what you may see in C-like languages.

Most languages use block-level scoping. JS doesn't. It uses function-level scoping. You should keep this in mind at all times, as it is probably one of the greatest sources of confusion for newcomers.

So what happens if we execute this piece of code?

(function() {
  var a = 10;

  if (true) {
    var a = 35;
  }

  alert(a);
})();

Yes, it alerts 35. The same kind of program written in C would output 10 (provided you really re-declare your variable inside your block).

Well that's the first surprise. And not the last, nor the least.

JavaScript variables declaration

Well, let's see what happens when we declare a variable.

Let's take the following code:

var a = 10;
alert(a);

(function() {
  alert(a);
  var a = 200;
  alert('a now contains: ' + a);
})();

What do we have here? The first alert says "10", as we could expect. But the second one alerts "undefined". Why on earth would a be undefined? Try to remove the "var a = 200;" line. The second alert says "10" again? Right. So this declaration / initialization line has something to do with this strange behavior. No matter where you declare a variable in your function, this variable will be declared anywhere in this function. What about the initialization? It stays right where you wrote it.

Eventually, JavaScript hoisting

Wow wow wow... What's that? Do you mean JS doesn't care about how I write my code? Not really. In fact, the previous piece of code will be interpreted like so:

var a = 10;
alert(a);

(function() {
  var a;
  alert(a);
  a = 200;
  alert('a now contains: ' + a);
})();

In fact, all the variable declarations, but not the initializations, are put at the top of your function. This is commonly called hoisting.

Note that this works with all declarations. Even the functions declarations. Be careful though, as the variable-like defined functions will only see their name hoisted (as we saw in the previous example with variable a), but not their body. "Traditionally" declared functions will be entirely hoisted (name and body). Here is a little example you can run to understand this phenomenon:

(function() {
  f1(); // Will run OK
  f2(); // Will throw an error

  f1() {
    alert("I'm in function f1");
  }

  var f2 = function() {
    alert("I'm in function f2, but I will never run before the f2 initialization...");
  };
})();

That may seem quite surprising, but that's how JS works. I can't say if that's a good thing or a bad thing, honestly, I don't see any advantage or drawback. It's just another way to work. As it pushes us to keep a clean code, with all vars declared at the top, it may be a good thing.

Speaking of code quality, your code won't pass JSLint (when you select "the good parts") if you don't declare all your variables at once in each function.

But what should I do then?

This is why you should always declare your variables at the top of your functions. You'll have no bad surprises since you respect this rule.

I hope this post was useful, and that it will help you achieve a better code quality.

Comments (8) Trackbacks (0)
  1. I was looking for a good example and definitive info on the order of declaration and initialization of JS variables and found your excellent article. Thank you very much!

  2. I’m studying that feature.THX.

  3. Bon ba ce poste va aller sur un blog perso

  4. Link exchange is nothing else however it is just placing the
    other person’s website link on your page at appropriate place and
    other person will also do similar in favor of you.

  5. It is not my first time to visit this website, i am visiting this website dailly and obtain good data from here daily.

  6. In addition to to admit you’re American, typical.

  7. I’mimpressed, I have to admit. Rarely do I come across a blog that’s both educative
    and engaging, and let me tell you, you have hit the
    nail on the head. The issue is something too few folks are speaking
    intelligently about. I’m vewry happy I found tis iin myy hunt for simething relating to this.

  8. Hello, of course this paragraph is actually pleasant and I have learned
    lot of things from it on the topic of blogging. thanks.


Leave a comment

(required)

You can use basic HTML to enlighten your comments. If you want to post some code, please use the <pre> tag. You can also use syntax coloring by adding class="syntax [language]". <pre class="syntax js"> will color your code as if it was JS code for instance.

No trackbacks yet.