3

I am a beginer to javascript.I have a doubt.my code is given bellow.when i run this the 1st alert box displaying "undefind".i can not understand why?thanks alot..

<html>
<head>
<script type="text/javascript">
var a = 123;
   function foo()
   {
     alert(a);
     var a = 890;
     alert(a);
   }
     foo();
     alert(a); 
</script>
</head>
<body>
</body>
</html>
DjangoDev
  • 889
  • 6
  • 16
  • 25

3 Answers3

4

This is because after hoisting but before execution, your foo() function internally looks like:

function foo() {
    var a; // declaration hoisted to top
    alert(a); // the local var is 'undefined' at this point
    a = 890; // assignment operation not hoisted
    alert(a);
}

Read more about hoisting here:

techfoobar
  • 65,616
  • 14
  • 114
  • 135
1

I believe this is because of variable declaration hoisting. Variable declarations are hoisted to the top of its scope. So that means, technically, your code is executed like this:

var a;
a = 123;
function foo()
{
  var a;
  alert(a);
  a = 890;
  alert(a);
}
foo();
alert(a); 

In this scenario, a is first defined globally, with an undefined value. Then, its value is set to 123. When the function is called, a new a is declared immediately in the function with an undefined value as a local variable, and that's why undefined is alerted at first. Then, you set its value to 890. So even though you use var in the middle of the function, it doesn't mean that's how it's executed, because of hoisting.

Ian
  • 50,146
  • 13
  • 101
  • 111
0

You initialize the variable a twice which gives the weird result. As now it is scoped twice differently.

<html>
<head>
<script type="text/javascript">
var a = 123;
   function foo()
   {
     alert(a);
     a = 890;
     alert(a);
   }
     foo();
     alert(a); 
</script>
</head>
<body>
</body>
</html>
Techmonk
  • 1,459
  • 12
  • 20
  • Can you explain why this is wrong? – Techmonk Feb 08 '13 at 06:14
  • Can you explain why this is correct? There's no real explanation of the problem, no real explanation of your code, and code that doesn't relate to the original. The original code redeclares the `a` variable in the function, so there's no reason for you to assume it should be a global variable throughout the whole code. I'm sure the OP has a reason for redeclaring `a` locally, and there's nothing wrong with that. The point is the confusion that ensues with variable hoisting. – Ian Feb 08 '13 at 06:20