The reason is that Common JS modules are not only used in node.js but also in a variety of other environments.
Many Common JS modules can be used in browsers as well. Each module gets its own function wrapper to isolate it from other modules. In that case it's necessary to use var
so that you don't accidentally leak into the global scope.
That being said most developers prefer to use var
explicitly in their code for the following reasons:
- It's a good programming practice. Seriously, programming is all about practice. I'm so used to declaring variables using
var
that I often find myself using var
declarations in C/C++ and then have the compiler cry at me.
- Variables declared using
var
cannot be deleted using the delete
operator. Sometimes I purposely omit var
in global variables so that I can delete them later and operate in "ninja mode".