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?