javascript variable scope in function confusion
Asked Answered
I

3

5

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?

Internist answered 10/3, 2014 at 18:30 Comment(3)
hoisted concept of javascript.Ricciardi
okay. please explain in form of answer. And links will be helpfull too.thanks.Internist
javascript memory management: developer.mozilla.org/en-US/docs/Web/JavaScript/…Evenings
E
10

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.

Enzymology answered 10/3, 2014 at 18:34 Comment(0)
G
3

In the first code snippet there is only one variable. The a outside the function and the a inside the function both refers to the global variable.

In the second code sniper there are two variables named a, one outside the function and one inside the function. As variables have function scope, the local variable inside the function exists in the entire function, not just after the line where it's defined. The declaration gets hoisted to the top of the function, while the assignment still happens where it's written.

Gaudette answered 10/3, 2014 at 18:39 Comment(0)
W
0

I'm not totally sure of this but I think I can tell you the reason:

When the source-code of the second function is parsed, the browser will know that there's going to be declared a variable 'a' in this function.
'var' tells it that 'a' should be a new variable within the function scope (not global). If there was no 'var' (like in first function), it will use the variable 'a' that's already declared in global scope.

So when it starts to execute the function, it allocates memory for it (and all other variables that are about to be declared in the function). Because 'a' is only defined but not yet initialized when the 'alert()' function accesses 'a', it returns 'undefined'.

Some tricky scope topic here :)

Wivestad answered 10/3, 2014 at 18:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.