0

I have some functions and variables:

function b() {
  myvar = 1;
  console.log(myvar);
  a();
}

myvar = 5;
a();
b();
a();

function a() {
  console.log(myvar);
}

The console log output is: 5, 1, 1, 1. Why is the last a() call getting "1" as output and not "5" ? Because I thought a() is called from global context, and this global context has myvar=5 as its outer (one level up) variable?

CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
Marc_L
  • 2,826
  • 7
  • 37
  • 68

1 Answers1

2

There are no local variables in this code - every variable name reference is a reference to a global variable, so whenever a reassignment happens, that global variable will be reassigned.

If b reassigned a local variable named myvar, you'd be correct, for example, if myvar inside b was a parameter, or declared with var/let/const inside b:

function b() {
  // next line has "var",
  // indicating that whenever the following variable name is used inside this function
  // it'll be referring to a local variable, not the global `myvar`:
  var myvar = 1;
  console.log(myvar);
  a();
}

myvar = 5;
a();
b();
a();

function a() {
  console.log(myvar);
}
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
  • ok thanks you are correct, I forgot to declar myvar with "var" in b()... didn't know javascript was that delicate.. those details really matter ;) – Marc_L Jan 14 '19 at 00:02