I have a fairly good grasp of the concepts of scope and closures in JavaScript.
Moreover, the following sites provide examples of how JavaScript namespaces can be implemented:
What I still do not understand is how many people seem to mix the concepts of scope and namespace. Furthermore, the same people often also mention how one should not "pollute the global namespace" and not "create global variables / variables in the global scope".
Questions
- Is it not correct that scope and namespace are two completely different concepts?
- Namespace: Grouping of code such that names within the group are unique and cannot collide with similar names in other namespaces
- Scope: Defines the accessibility of variables. JavaScript has two scopes, global and local/function scope (ES 2015 introduced block scope with
let
/const
)
- Is it correct that the following object literal creates a new namespace for
bar
, avoiding to pollute the global namespace (except forfoo
), but thatbar
is still in the global scope:var foo = { bar: 42 }
- Is it not wrong to say "don't create global variables so you do not pollute the global namespace"? Global vs local variables (scope) is different from namespacing. As seen, it is perfectly possible to shield a variable in a new namespace, and still have it be in the global scope.
- If avoiding to pollute the global namespace is the only reason for why we should not create global variables, is it not enough to just create new namespaces and still keep it all global?