Here are 2 javascript functions
var a = 10;
function abcd()
{
alert(a);//alerts 10
a=5;
}
And another code is this
var a = 10;
function abcd()
{
alert(a);//alerts undefined
var a=5;
}
In both function assignment/declaration is after alert() call.
Then why alert message are 10
and undefined
respectively?
The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
You can access such variables inside and outside of a function, as they have global scope. The variable x in the code above was declared outside a function: x = 10 . Using the showX() function, we were still able to access x because it was declared in a global scope.
A function in JavaScript defines a scope for variables declared using var , let and const . Any variable declared within that function is only accessible from that function and any nested functions. A code block ( if , for , etc.) defines a scope only for variables declared with the let and const keywords.
Variables declared with var will be auto-initialized to undefined within their scope, even if you reference them before they're declared. The big problem is that undefined doesn't always mean you're using a variable before it's defined.
That's because your variable gets "hoisted" up of its containing scope by the interpreter when you declare it. So your code ends up being interpreted like this:
function abcd()
{
var a;
alert(a); //alerts undefined
a = 5;
}
To avoid this kind of confusion, you can follow some practices that will keep things in place, like declaring your local-scoped (that is, variables declared with the keyword var
inside a function scope) variables right in the beginning of the function.
Note that, as you can read from the article, this happens with nested functions aswell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With