user1637281
user1637281

Reputation:

When does hoisting apply?

I use this pattern for some of my code:

(function () {
    var a,
        b,
        c,
        d;

    a = // some module definition
    b = // some module definition
    c = // some module definition
    d = // some module definition

}());

What I've noticed is that if b needs access to a it must be defined before it. So b can reference a, but a can not reference b.

I found this strange because I thought a process called hoisting allowed me to not have to define my modules in any particular order.

But what I'm finding is that ordering does matter.

Upvotes: 1

Views: 72

Answers (2)

yowza
yowza

Reputation: 249

Only the var declaration is hoisted. Not the = assignment.

This means you can refer to a variable whose var declaration comes later in the function without getting a ReferenceError, but its value will be undefined until the assignment actually takes place.

(function() {

    alert(b);  // undefined
    var b = "foo";
    alert(b);  // "foo"
})();

Because of the "hoisting", the above example effectively turns into this:

(function() {
    var b;
    alert(b);  // undefined
    b = "foo";
    alert(b);  // "foo"
})();

Upvotes: 4

Coin_op
Coin_op

Reputation: 10728

Hoisting means the declaration happens earlier but the assignment doesn't move. The variable will be declared but will be undefined.

Hoisting can cause confusion due to scoping issues. So for instance:

var a = 1;
var somFunc = function(){
  var b = a;
  alert(b); // alert undefined
  var a = 3
}
someFunc();

The alert in this case is 'undefined' as the second var a is hoisted above the var b, but the assignment is left till after, and the first a assignment is overwritten because it is outside the scope.

Upvotes: 2

Related Questions