qwe
qwe

Reputation: 175

Variable name is like function name -- when causes error/when doesn't

This question is about the same names of function and variable. Please tell me - why this code doesn't have errors:

    var Task = new Task();
     
    function Task() {
        console.log('work!');
    }

but this one won't work:

start();
 
function start() {
  var Task = new Task();
};
 
function Task() {
    console.log('work!');
}
 

Why it's so?

Upvotes: 5

Views: 74

Answers (1)

deceze
deceze

Reputation: 522042

Through name hoisting, your first code essentially works like this:

var Task;  // (undefined)

Task = function () {
    console.log('work!');
};

Task = new Task();

Your second one like this:

var start, Task;

start = function () {
  var Task; // (undefined)
  Task = new Task();
};

Task = function () {
    console.log('work!');
};

start();

As you can see, Task is being overridden by undefined inside the start function. This does not happen when the function and variable definition are both in the same scope, since then var and function are essentially the same thing.

If you leave out the var inside start, it works as well.

Upvotes: 6

Related Questions