I know that if a variable in defined inside a function, with var keyword, then it will have Local Scope. When I tested following in Console of Browser, first output was undefined. Why?
nw1 = 1; function nwf() { alert(nw1); var nw1 = 2; alert(nw1); }; nwf();
Because you declared nw1 using the var keyword within the closure of the function, it has function-wide scope even tho' the declaration falls after the initial reference. The local variable shadows the global one within the scope of the function, and the local variable is undefined locally at the first point you reference it.
Praveen Bayyana
Web developer
This is what the concept of 'hoisting' is about in Javascript. Anything can be used before the declaration of it (but limited to the scope within which it's declared).
JS brings all the declarations to the beginning of the block as part of interpretation. That's how the local variable inside the function is shadowing the one defined in the global scope. Since JS can hoist only declarations and not initializations, the value of the variable in the function scope is 'undefined' when it was accessed in the first alert.