Reputation: 1072
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.
Upvotes: 1
Views: 204
Reputation: 3844
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);
Upvotes: 3