-2

Please provide an explanation why the output will be 4. I am trying to understand that the output is 4 but cannot find the reason why is it not 3.

var x=4,
obj={
    x: 3,
    bar:function(){
        var x = 2;
        setTimeout(function(){
            var x=1;
            console.log(this.x);
        },1000);
    }
}

obj.bar();
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `this` in the `setTimeout` callback is the global object, because this code is in loose mode rather than strict mode. It's also at global scope, so the `var x` at the top becomes a property of the global object. So `this.x` is `4` inside that callback. – T.J. Crowder Aug 27 '21 at 09:00
  • I strongly recommend always using [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), either by A) Using [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), which are strict by default; or B) Putting `"use strict";` at the top of the file. Strict mode fixes several issues with the language, not least [implicit globals](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) like your `obj` (the lack of declaration should make using it an error). – T.J. Crowder Aug 27 '21 at 09:02
  • In strict mode, your code would fail with "TypeError: Cannot read property 'x' of undefined" because `this` inside the `setTimeout` callback would be `undefined`. – T.J. Crowder Aug 27 '21 at 09:02

1 Answers1

0

You are using this.x inside the function of setTimeout, thus it is printing 4, however, if you do not use this.x it shall print 1 to the console. You must remember that the **this** keyword behaves differently in JavaScript compared to other languages. In JavaScript, the value of **this** does not refer to the function in which it is used or its scope but is determined mostly by the invocation context of function (context.function()) and where it is called.

As you see in the above example **this** in setTimeout function does not refer to the lexical scope of the function. But refer to global scope because it’s the invocation context of the function.

Satya
  • 1,569
  • 8
  • 13