Skip to content

Namespaces in JavaScript

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: