How to avoid namespace pollution in Javascript

efpage

Eckehard

Posted on August 9, 2021

How to avoid namespace pollution in Javascript

I found this brilliant post about namespace pollution, which notes that - beside of conflicting name definitions - using global variables may have impact on memory consumption (see also this post):

"As variables lose scope, they will be eligible for garbage collection. If they are scoped globally, then they will not be eligible for collection until the global namespace loses scope..."

In languages like C++ or Delphi, naming conflicts between libraries can easily be solved: If there are identical names in different libraries, the name can be qualified by adding the library name:

  • libA defines myVariable
  • libB defines myVariable

Your app can use libB.myVariable or libA.myVariable or myVariable, if no conflict occured - Simple solution

In Javascript, name clashes cannot be solved this way. For Variables, we can use var instead of let, but this may cause hard to track errors. For functions, I currently see no such solution.

Using named imports of modules is not a similar elegant solution. I was wandering, if there are better solutions or recommendations for Javascript?

💖 💪 🙅 🚩
efpage
Eckehard

Posted on August 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related