Namespaces in JavaScript
What is namespacing?
Namespacing is the act of wrapping a set of entities, variables, functions, objects under a single umbrella term.
JavaScript has various ways to do that, and seeing the examples will make the concept easier to understand.
The simplest way to create a namespace is by creating an object literal:
const car = {
start: () => {
console.log('start')
},
stop: () => {
console.log('stop')
}
}
In this way, start and stop are namespaced under car
: car.start()
and car.stop()
.
They are not polluting the global object.
Why is this important? One good reason is that nothing can interfere with them.
The way works also by assigning a variable to an object after it’s created:
const car = {}
car.start = () => {
console.log('start')
}
car.stop = () => {
console.log('stop')
}
But they are still accessible from the outside, thanks to the car
object reference.
The best way to completely hide code from the outside is to wrap it into a block, which is a part of code wrapped in curly brackets, like an if
or for
block, but also an independent block formed like this:
{
const start = () => {
console.log('start')
}
const stop = () => {
console.log('stop')
}
}
Those 2 functions are now inaccessible outside of the block.
But you need to pay attention at always using let
or const
, which are block scoped.
Using var
instead would “leak” it outside of the block.
To workaround that you can use functions, which is the “old”, pre-let/const way:
(function() {
var start = () => {
console.log('start')
}
const stop = () => {
console.log('stop')
}
})()
Now start
and stop
are both inaccessible from the outside, even if start
is assigned to a variable defined with var
.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025