How to avoid namespace pollution in Javascript

Eckehard - Aug 9 '21 - - Dev Community

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?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .