3

Consider the following code

var scope = "global scope";
function checkscope() {
    console.log(scope);
    var scope = "local scope";
    console.log(scope);
}
checkscope();

This prints the following in the console

undefined
local scope

Why is the first console.log printing undefined instead of "global scope"?

1 Answer 1

6

It's because of hoisting. Your var keyword is hoisting a new local scope variable to the top of the function, which is undefined.

Your code is the same as:

function checkscope() {
    var scope;
    console.log(scope);
    scope = "local scope";
    console.log(scope);
}

To access the global scope from within the function, you would have to reference the global object, which is window for browsers. This will work if the global scope is actually global, and not just in a parent scope of checkscope().

function checkscope() {
    console.log(window.scope); // access the global
    var scope = "local scope";
    console.log(scope);
}
Sign up to request clarification or add additional context in comments.

4 Comments

And is there a way to acces the variable containing global scope?
var scope; // initially undefined
@devian if it's truly global, then window.scope would work. But don't do that unless you really have to.
@devian if you want to access the local scope variable from the global scope then no it's not accessible. If you want to access the global scope variable from in the function then window.scope will work.

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.