74

What is the node.js equivalent of window["myvar"] = value?

Naftali
  • 144,921
  • 39
  • 244
  • 303
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286

1 Answers1

108

To set a global variable, use global instead of window.

global["myvar"] = value
  • 1
    @Dokkat: `window` and `global` are just references to the global object in their respective environments. So you use them the same way in each environment. I updated my answer to show the code explicitly. –  Jun 11 '12 at 17:19
  • @am_not_i_am I know, but it is more clear this way. Thank you. – MaiaVictor Jun 11 '12 at 17:21
  • 16
    Note, however, that using Node's `global` should be done sparingly if at all. If there's some other way to share data between modules, use it instead. In particular, if you ever find yourself needing to use Cluster or some other way of distributing your app between processors, using `global` will break down because it won't be shared between the sub-processes. – ebohlman Jun 11 '12 at 23:26
  • 4
    not work ! `var foo = 42; console.log(global.foo); //return undefined...` – Matrix Sep 26 '16 at 00:23
  • @Matrix: What does `var foo = 42` have to do with my answer? Where do you see a `var` declaration? –  Sep 26 '16 at 01:57
  • 1
    @squint because in the browser if you run `var foo = 42; console.log(window.foo);` you would get the output `42` in the console. since that doesn't work with `global` in node, then it's hard to call it an equivalent. – spex Jan 16 '17 at 08:26
  • 4
    @spex: It works the same in node and the browser. In both cases, if you do `var foo = 42` in the global environment, you'll be able to access `foo` as a property of the global object, which is `window` in the browser and `global` in NodeJS. However, if you do `var foo = 42` in a *module*, you're not in the global environment; you're inside a function. Irrespective of this, the question isn't about using `var` to create a variable; it's about how to create a property directly on the global object. –  Jan 16 '17 at 13:20
  • 7
    @squint I understand, not sharing my own confusion but explaining why @Matrix is confused. He's not seeing `window` and `global` as equivalent in his specific case and so is saying they are wholly not equivalent. – spex Jan 17 '17 at 17:24