2

I've embarked on a mission to actually explore and try to deeply understand Javascript. On my journey I've come up with the following code and I'm troubled by the output, especially since I can't seem to explain its output yet it throws no errors:

var test = 1;
var func = function(){
    console.log(test);
    for(x=0;x!=1;x++) {
        var test = test + x;
        console.log(test);
    };
};
console.log(test);
func();

I would expect the output to be:

1
1
1   (or possibly an error due to scoping issues)

What I actually get is:

1
undefined
NaN

I can buy the NaN since, in my mind, I've locally scoped a variable named test and I'm initializing it to itself plus x. I could see that as an obvious fail, yet no error is thrown. The one that really puzzles me is the "undefined." Shouldn't that output the globally scoped test?

2
  • Basically, assigned functions won't get parent scope. Commented Dec 19, 2015 at 20:42
  • Araymer: that doesn't make sense. Clearly, even assigned functions will have global variables in scope; otherwise there's no point in globally scoping something! The problem is precisely what @Thomas explains. Commented Dec 19, 2015 at 20:47

1 Answer 1

4

Javascript is function scoped, not block scoped. Furthermore, var declarations are hoisted to the top of the function definition. So your code is equivalent to this:

var test = 1;
var func = function(){
    var test;
    console.log(test);
    for(x=0;x!=1;x++) {
        test = test + x;
        console.log(test);
    };
};
console.log(test);
func();

This is why some people (e.g. Doug Crockford, author of jslint) advocate always putting declarations at the top of the function, because that's how the interpreter reads them anyway.

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

4 Comments

Ahhh... Thank you Thomas! That makes sense.
I agree with David Hoelzer. One more comment is the variable x in this function is a global variable. By not having a var x, you may be stepping onto some global variable.
Oh, that's super important. Thanks @Will. I was unaware of that.
Strict mode will help you catch such mistakes by requiring that every variable be declared.

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.