Code with var variable at each level gives unexpected result

26 views Asked by At

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();

1

There are 1 answers

0
UTKARSH KOUSHIK On

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.