Why am I getting this error in VSC with the "this" keyword

Code:

function foo () {
console.log(“Simple function call”);
console.log(this === window);
}

foo();

Output:

[Running] node “c:\Users\David Garcia\Desktop\CODING\PRACTICE\JS\script.js”
Simple function call
c:\Users\David Garcia\Desktop\CODING\PRACTICE\JS\script.js:3
console.log(this === window);
^

ReferenceError: window is not defined
at foo (c:\Users\David Garcia\Desktop\CODING\PRACTICE\JS\script.js:3:24)
at Object. (c:\Users\David Garcia\Desktop\CODING\PRACTICE\JS\script.js:7:1)
at Module._compile (node:internal/modules/cjs/loader:1233:14)
at Module._extensions…js (node:internal/modules/cjs/loader:1287:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.5.1

[Done] exited with code=1 in 0.35 seconds

Goal: I’m trying to obtain this output:

“Simple function call”
true

Thank you for your reply. Yes, I am executing via the first way. I tried doing another code and did this on the browser and vsc but got different outputs.

Code:

var width = 600;
var shape = {width: 300};

var showWidth = function(){
return this.width;
}

showWidth();

Browser Output:
600

VSC Output:
It doesn’t show 600 but it did run the code with no errors.

How do I get to see output of 600 on VSC like how I see it on the browser?

It gave me a undefined when I ran this code in VSC:

var width = 600;

var shape = {width: 300};

var showWidth = function(){

return this.width;

}

console.log(showWidth());

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