简体   繁体   中英

Are Javascript variables not declared (no var) inside functions treated as global?

I have read many aritcles and even SO questions stating that javascript variables not declared inside the functions are treated as global. "no var" inside function will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

Here is a SO link for this.

What is the purpose of the var keyword and when to use it (or omit it)?

But when I thought to execute it, it gave me error right away.

function foo() {
    // Variable not declared so should belong to global scope
    notDeclaredInsideFunction = "Not declared inside function so treated as local scope";

// Working fine here
    alert(notDeclaredInsideFunction);
}

// Giving error : notDeclaredInsideFunction is undefined
    alert(notDeclaredInsideFunction);

So notDeclaredInsideFunction should have been treated in global scope. But why I am getting error that states that notDeclaredInsideFunction is not defined. May be I am missing something very simple.

Function is declared, but never called so that is why its giving an error. Try this

function foo() {
    notDeclaredInsideFunction = "Not declared inside function so treated as local scope";
    alert(notDeclaredInsideFunction);
}
foo();

alert(notDeclaredInsideFunction);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM