0

I am new to coding and cannot figure out the following code. If anyone can give me a hand I will deeply aprreciate!!

function a() {
  function b() {
    console.log(x);
  }
  var x = 2;
  b();
}
var x = 1;
a();

When I run this code it makes perfect sense that the console is 2. Super!

But when I run this code:

function a() {
  b();

  function b() {
    console.log(x);
  }
  var x = 2;
}
var x = 1;
a();

When this code runs, I would have thought that the console answer would be 2 as well! but I get undefined as the answer. At least I would have thought that 1 could be the answer in case it was not 2, but never ever: undefined.

Can anybody please give me a hand?

Many thanks!

FZs
  • 16,581
  • 13
  • 41
  • 50
Tesa
  • 47
  • 4

2 Answers2

4

var declarations are hoisted.

That means that these declarations are moved to the top of the current scope (function) at compile time (before the code runs).

Hoisting does move the variable declaration, but does not move the variable assignment.

Thus, this code:

doSomething();
var variable = value; //Declaration with assignment

is transformed to:

var variable; //Declaration
doSomething();
variable = value; //Assignment

So, your code is identical to the following:

function a() {
  var x; //x is now undefined
  
  //Function declarations are hoisted as well:
  function b() {
    console.log(x);
  }
  
  b(); //x is still undefined now...

  x = 2; //x is now 2, but your console.log has already run.
}
var x = 1; //This line doesn't affect your code, as the x you log is in different scope, and the internal x shadows this one.
a();
FZs
  • 16,581
  • 13
  • 41
  • 50
0

so x is undefined in your second example because of the fact that you initialized x (i.e. var x = 2) after you called function b (i.e. b()). That means the program does not know what x is yet when you called function b so when you do call b() you are trying to print something you have not yet defined to the program.

The first example works because x is defined before the function call to b

bturner1273
  • 660
  • 7
  • 18