0
<html>
<body>
<script type= "text/javascript">

var i=10;
function f(){
   alert(i);
   if(!i){
     var i= 20;
   }
   alert(i);
}
f();
</script>
</body>
</html>

This is my html file. The outputs I get are undefined for first alert and 20 for the second alert. Why is this so? What is happening here?

Anirudh K
  • 144
  • 1
  • 13

1 Answers1

0

I believe it's because the i is hoisted, but the assignment of i is not. Therefore, when you alert i, it is referring to the locally scoped i which hasn't yet been assigned a value.

It ends up working like this:

var i;
alert(i);
if(!i){
    i = 20;
}
beartech1
  • 149
  • 1
  • 1
  • 10