Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable scope in function confusion

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?

like image 629
Rohit Awasthi Avatar asked Mar 10 '14 18:03

Rohit Awasthi


People also ask

Is VAR globally scoped?

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

Are variables declared inside a function accessible outside it?

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.

Which two factors determine the scope of a variable in JavaScript?

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.

What are the scope problems caused by VAR?

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.


1 Answers

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.

like image 64
Natan Streppel Avatar answered Oct 03 '22 14:10

Natan Streppel