Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are namespaces considered bad practice in JavaScript? [closed]

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.

like image 976
Eliran Malka Avatar asked Dec 12 '22 03:12

Eliran Malka


1 Answers

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

  • node-browserify
  • webmake
  • modul8

Further reading:

  • Modularity without globals
  • CommonJS modules
like image 125
Raynos Avatar answered Apr 20 '23 21:04

Raynos