Friday 8 February 2019

Why are namespaces considered bad practice in JavaScript?




I've been told namespaces shouldn't be used, as they 'pollute' the global scope. I wonder what are the alternatives?




When I want to define utility functions and / or constants e.g. for a website, a simple way to go would be to define them by namespaces, that way the damage to the global scope is restricted to one object only.



If namespaces are bad practice, a couple of questions comes to mind:




  1. Why is this bad practice?

  2. What's the scope of this declaration (web applications / dynamic websites / static websites etc.)?

  3. What are the alternatives?




This question is a result of a discussion started on a post on the benefits of using extend.js.


Answer




why is this bad practice?




namespaces themself are bad because it's an unnecessary concept.



Having objects with properties and methods is acceptable. It's also fine to have a "module" token which is similar to a "namespace" but instead the meaning is that you have one "module" token per file which contains all your properties and methods. This is different from a "namespace" because it's only created / altered in a single file and isn't exposed as a global token.





what's the scope of this declaration (web applications / dynamic websites / static websites etc.)?




All ECMAScript, never create new global tokens




what are the alternatives?





Rather then having namespaces you should favour multiple "file local" tokens. Meaning that each file / "module" should be wrapped in a closure and you should have access to multiple local variables inside this closure.



Global variables are also bad because you don't need them, at all, ever. The way you avoid globals is by wrapping everything in closures and being intelligent in how you load external javascript files.



Examples of zero global module loaders





Further reading:





No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...