Javascript returns undefind for globally declared variable

I am a javascript beginner. I have a questionable .my code below. When I run this first alert box showing "undefind". I can't figure out why? Many thanks.

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

      

+3


source to share


3 answers


This is because after hoisting but before execution, your function foo()

internally looks like this:

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 lifting here:

+4


source


I believe this is due to hoisting variable declarations. The variable declarations climb to the top of its scope. So, technically, your code runs like this:

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

      



In this case, it is a

first defined globally, with a value undefined

. Then its value is 123

. When a function is called, a new one is a

declared immediately in the function with the value undefined

as a local variable and is therefore undefined

alerted first. Then you set the value 890

. Therefore, even though you are using var

in the middle of a function, it does not mean that it was executed due to a lift.

+1


source


You are initializing the variable a twice, which gives a strange result. Since now it has scope twice in different ways.

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

      

0


source







All Articles