0

Here is a tricky interview question that I am struggling to answer, much less give a clear explanation of why this code outputs undefined.

  var x = 21;
    var girl = function() {
      console.log(x);
      var x = 20;
    };
    girl();

So, the x = 20 is below the console.log - Javascript hoists the variable, but why doesn't it output it as 20? Ok, let's imagine, it ignores the variable that was declared below the console.log - why doesn't it look in the global scope? Who can make it clear for me? I'd appreciate it.

ellipsis
  • 12,049
  • 2
  • 17
  • 33

1 Answers1

3

The "internal representation" of the code is something like

var x = 21;
var girl = function() {
  var x;  // (equals `var x = undefined`)
  console.log(x);
  x = 20;
};
girl();

That probably clears it up.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • I would add just that `var x;` "overwrites" inside the function context the `x` variable declared outside the function. – lealceldeiro Sep 26 '19 at 11:02
  • 2
    @lealceldeiro "Overwriting" sounds like it does affect the outer variable. The term you're looking for is "shadowing". – Bergi Sep 26 '19 at 11:04
  • @lealceldeiro `console.log(x)` outside the function will still log `21`. So, it doesn't overwrite. – adiga Sep 26 '19 at 11:05
  • @Bergi thanks. That's the term I was looking for :) I'm not a native English speaker ^‿^ – lealceldeiro Sep 26 '19 at 11:48
  • @lealceldeiro variable shadowing is a technical term, I doubt most native English speaker would come up with it :-) – Bergi Sep 26 '19 at 13:15