DEV Community

Discussion on: Why Do JS Devs Hate Namespaces?

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I always look at JS from the perspective of a Lua developer, since that's my main language and they are both very similar in many aspects.

The lack of namespacing has always seemed a bit weird to me. The Lua equivalent to JS objects, tables, is used for namespacing almost everywhere, with most library code looking like this

local lib = {}

function lib.foo()
end

function lib.bar()
end

return lib
Enter fullscreen mode Exit fullscreen mode

yet in javascript nobody does this, despite it being possible in just the same way (except for the syntax, of course).

const lib = {}
lib.foo = (a) => a+1
lib foo = (a) => a*2
Enter fullscreen mode Exit fullscreen mode

For small sections of code, what JS was originally built for, this may be enough, but for larger codebases this just seems like just a valuable tool that I wonder just how the whole JS community never started adopting this. Then again, maybe it's just a leftover from those times when JS really was just used for simple interactivity on plain hand-written HTML pages.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

yet in javascript nobody does this, despite it being possible in just the same way (except for the syntax, of course).

I appreciate that confirmation! As I was writing the article, I couldn't help but wonder whether this lack of namespacing was just in my head. But yeah - I don't understand why the approach you've shown above is almost never taken in JS.

In fact, as I outlined in the section about destructuring, it honestly feels to me like JS devs are ruthlessly going in the other direction - purposely stripping variables of all context. I'm not exaggerating when I say that I've read JS code where I had to repeatedly refer back to the top of the function to understand the values that particular variables were supposed to hold - because all of those variables had been destructured out of their original object.