1

In browser javascript, when a variable is declared with var, it is appended to the window object, which may cause overriding if another variable with the same name declared with var is used by the same or other file in the window. That's why some people say that "var variables are global" and should be avoided:

//Browser JS
var my_var = 3
let my_let = 3

console.log("window.my_var = " + window.my_var)
console.log("window.my_let = " + window.my_let)

returns

3
undefined

As expected.

Similarly, node has the global object. I knew var declared variables wouldn't be appended to global since node works with module. However, it seems that var declared variables are not appended to module object:

//Node JS
var my_var = 3
let my_let = 3

console.log("module.my_var = " + module.my_var)
console.log("module.my_let = " + module.my_let)

returns

module.my_var = undefined
module.my_let = undefined

Why is my_var not appended to module? Does it have module scope? Is it appended elsewhere? What's the difference between var and let in node?

abcson
  • 157
  • 9
  • Node modules run in their own function, so they don't get put onto the global object. The benefits of `const` (and, if you really have to, `let` ) are that they have more intuitive block scope and a DMZ. – CertainPerformance Nov 15 '19 at 23:37
  • Please open my question again. The linked question does not answer what i asked. I already knew vars would have the module scope, which is answered by the link you posted, i want to know why it's not appended to the module object. – abcson Nov 15 '19 at 23:39
  • It's because variables declared in a function *never* get assigned as properties of that function (unless you do so explicitly, like `module.my_var = 'foo'`, which is pretty weird) – CertainPerformance Nov 15 '19 at 23:40
  • But browsers do that with the ```window``` object... – abcson Nov 15 '19 at 23:45
  • No they don't - the window object is not a function all code executes inside of. The window object is just a (non-function) object. – CertainPerformance Nov 15 '19 at 23:48
  • The thing referred to by `module` is just a plain object. It's not a "scope" where declared variables are put in. – Bergi Nov 16 '19 at 03:35

0 Answers0