1

I am learning javascript global variable and local variable. When I did experiment with it (see jsfiddle below) then I am confuse that why after executing myFunction1() the value of variable a became 4 instead of 5. What do you think happened inside the javascript memory which made its value 4 instead of 5 ?

var a = 4;

myFunction1();
function myFunction1() {
  a= 5;
  var a= 6; 
} 
alert(a); //a = 4


myFunction2();
function myFunction2() {
  a= 5;
} 
alert(a); //a = 5
CodingFriend
  • 149
  • 1
  • 12
  • 1
    See duplicate reference. Simply put: a `var` in a function body makes that variable a *local* variable in the *whole* function body, so any use of that variable in that body -- even when occurring before the `var` statement -- concerns that local variable. – trincot Jul 30 '21 at 14:09

1 Answers1

2

You've just discovered hoisting.

By declaring var a inside the function, it is available to the whole function context (even before its declaration), so when you write a = 5 the actual a is not the one you expect, it's the function-scoped a.

In the second case, a is the one you expect (outside the function)

Guerric P
  • 30,447
  • 6
  • 48
  • 86