4

I am trying to understand this keyword. but the problem is with the node environment. I am getting the expected behavior in Chrome Developer tool but the same code isn't working fine in the node environment.

When we create a var in the global context, it is supposed to be inside the global (node) or window (browser) but in node environment, it doesn't get attached to document.

I am just testing a simple 3 lines of code which works totally fine in chrome.

This is for Node environment

var color = 'red';

console.log(this.color);
console.log(global.color)

and this is for Browser which works fine

var color = 'red';

console.log(this.color);
console.log(window.color)

For the node environment, I am receiving undefined which is not expected.

Barmar
  • 596,455
  • 48
  • 393
  • 495
Arsalan Khattak
  • 498
  • 6
  • 13
  • 8
    In Node, code is always scoped to a *module*. – Pointy Jul 12 '19 at 15:09
  • 4
    Node.js files are implicitly wrapped in an IIFE, so it would be the equivalent of `(function () { var color = 'red'; console.log(window.color); })();` in a browser. – Patrick Roberts Jul 12 '19 at 15:10
  • 1
    [Related](https://stackoverflow.com/a/56908340/1541563). tl;dr _don't rely on `var` attaching to global namespace. Even when it works, it's confusing to those reading your code._ – Patrick Roberts Jul 12 '19 at 15:12

1 Answers1

3

Here's a software development rule: don't rely on variables sticking on this, global, or module-related objects. Scope can vary and lead to unexpected behavior and bugs. Use explicit (this|global|module.exports).varName bindings.

But if you just want to understand how things work in Node:

  • Code is wrapped into an IIFE when executed, setting the this value to module.exports (not global).
  • Access to global is persistent across modules, so if you write global.foo='foo' in a module then require it in bar.js, global.foo will be set to 'foo' in bar.js. It is discouraged to directly use global for most use cases - stick to exports and require.
  • According to the specs, var is not supposed to make things stick to global: there are some exceptions (see below), but you should not rely on that when writing code

Related questions:

Nino Filiu
  • 10,020
  • 6
  • 40
  • 53
  • Okay, so from what I understand is that this in nodejs refers to an empty object which is module.exports, right? Now please clarify me a little bit about global on nodejs. Does it refers to whole environment and our module.exprorts get attach to global? – Arsalan Khattak Jul 13 '19 at 00:40
  • Define *attach* – Nino Filiu Jul 13 '19 at 13:20
  • I mean module.exports make it a property of global. but nvm, I researched on it and clarified myself. – Arsalan Khattak Jul 13 '19 at 13:54