5

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?

10
  • 7
    I think the downvotes are a little harsh here - it's not immediately obvious why the redeclared Task variable works outside of the function but not inside. Commented Aug 25, 2016 at 14:35
  • 3
    @SterlingArcher Sure it is. The issue is one of scope and hoisting. I don't have time to go into a full answer now though... Commented Aug 25, 2016 at 14:37
  • 2
    @JamesThorpe yup, but no worries. deceze answered it well enough lol Commented Aug 25, 2016 at 14:38
  • 1
    First: why would you do that? Second: as described in the tour ´questions about an actual problem´, so please explain your problem. Commented Aug 25, 2016 at 14:46
  • 1
    @inetphantom Not understanding why code works the way it works is not a real enough question and/or problem? Commented Aug 25, 2016 at 14:48

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was typing up a similar answer, but I like this one much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.