0

I'm struggling to understand why the output of this command is not 10.

var x = 10;
console.log(this.x);

On the other hand, when x is global the output is indeed 10.

x = 10;
console.log(this.x);

how come in the first example it does'nt print '10'? x is a variable of "window" object, so 'this' should be window. what am i missing here?

Pointy
  • 371,531
  • 55
  • 528
  • 584
Lior
  • 1
  • 3
  • Where *exactly* in your JavaScript code does that first sample exist? Is it inside of a function? – Pointy Jul 24 '18 at 17:28
  • This is just a variable, not a const/variable within a scope (function, class etc.). So instead of using `console.log(this.x)` use `console.log(x)` – Variable Jul 24 '18 at 17:28
  • 1
    Apparently, `var x` in your first example is *not* a global `window` property. Why that is, we can't answer without more context. Please provide a [mcve] – Bergi Jul 24 '18 at 17:29
  • @Pointy - No. It's the first line of code. – Lior Jul 24 '18 at 17:29
  • If you're running this in a browser, and the first line of code really is `var x = 10;` followed by the `console.log()` call, then it would behave the same way as the second snippet. Are you using jsfiddle? If so make sure your JavaScript panel is configured properly because by default it puts the code in a window "load" handler. – Pointy Jul 24 '18 at 17:34
  • @Pointy Thanks! the problem was I was using jsfiddle! – Lior Jul 24 '18 at 17:38

0 Answers0