0

Running this code on VSCode:

Observe the code below :

value = 10;
console.log(global.value); // 10
console.log(this.value);   // undefined

Why does this.value evaluate to undefined and not 10? Doesn't the this keyword always point to the global object outside of a function?

noSelf_
  • 29
  • 5
  • 2
    Are you running this in a nodejs envrionment? If so, `this` refers to `module.exports` at the top level. – Nick Parsons Aug 20 '22 at 09:50
  • because global is undefined. Remove `global.` from the first `console.log` your code will work fine. – maddy23285 Aug 20 '22 at 09:52
  • 2
    @maddy23285 This looks like nodejs code. In nodejs [`global`](https://nodejs.org/api/globals.html#global) exists. OP would be getting a different error if `global` didn't exist. – Nick Parsons Aug 20 '22 at 09:53
  • 1
    If it helps in understanding how that's possible, nodejs [wraps your code](https://nodejs.org/api/modules.html#the-module-wrapper) in a module wrapper (for CJS modules), so that code above is actually in a function, just one you can't see. – Nick Parsons Aug 20 '22 at 10:07
  • @Nick Parsons I'm running this code using VSCode. Sorry if this info isn't helpful but I'm a total newbie to programming :) – noSelf_ Aug 20 '22 at 10:12
  • @noSelf_ That hints that it's nodejs, but when you run it in vs code, how do you do that? Are you running `node .js` to run it (or doing something like `npm start`/`nodemon` maybe?) – Nick Parsons Aug 20 '22 at 10:13
  • @maddy23285 As far as I know, I'm running this code in VSCode `without` strict mode. – noSelf_ Aug 20 '22 at 10:13
  • @Nick Parsons No I'm running it using VSCode shortcut for linux (alt + ctrl + n). – noSelf_ Aug 20 '22 at 10:15
  • @noSelf_ when you do that, does it show `[Running] node ...`? Like [this](https://i.stack.imgur.com/dU8eB.png)? – Nick Parsons Aug 20 '22 at 10:25
  • @Nick Parsons yes – noSelf_ Aug 20 '22 at 10:37
  • 1
    Nice, that means node is being used to execute your script. The above comments and links should cover what’s going on in your script – Nick Parsons Aug 20 '22 at 10:55
  • 1
    @Nick Parsons cool. I understood what you said about node modules. It makes sense now. Thanks! – noSelf_ Aug 20 '22 at 10:56

0 Answers0