Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

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 :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top