"this" inside a function

Hello fellow programmers and students,

I have come across a code snippet I can’t quite figure out.

function foo() {
console.log( this.a );
var a = 2;
foo(); // undefined

Why such an output when ‘a’ is declared in the global scope and ‘this.a’ inside the function resolves to the global object??? Shouldn’t the output be ‘2’? And no, this is not in strict mode. I ran this code on VS Code.

The funny thing is, when I run the same snippet on browsers, it outputs ‘2’

If someone would be kind enough to clear this up for me, I’d be immensely grateful. Cheers.

So where did you run it the first time, when it output undefined? Presumably, the undefined is just the return value of the function foo.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.