Namespace in JavaScript: What Does It Mean?

A namespace is a named container (variable) used to store objects of any type.

A namespace helps avoid ambiguity. It allows you to use the same object multiple times in the same script as long as you encase them in different namespaces.

Here’s the syntax:

keyword namespace = object;

Example: Name Collisions

Consider this code:

function myName() {
  return "My name is Oluwatobi.";
}

function myName() {
  return "My name is Sofela.";
}

function myName() {
  return "My name is CodeSweetly.";
}

console.log(myName());

// The invocation above will return:
"My name is CodeSweetly."

Try it on StackBlitz

The name collisions in the snippet above automatically gave the last myName function higher precedence over the previous ones.

However, what if you intended to invoke the second myName function? Here’s where namespaces become helpful.

A namespace allows you to put your objects into unique containers to prevent collision with one another.

Example: Namespace

const firstName = function myName() {
  return "My name is Oluwatobi.";
}

const lastName = function myName() {
  return "My name is Sofela.";
}

const websiteName = function myName() {
  return "My name is CodeSweetly.";
}

console.log(lastName());

// The invocation above will return:
"My name is Sofela."

Try it on StackBlitz

In the snippet above, we put each function into unique namespaces. As such, we were able to indicate the specific myName function the computer has to invoke.

Here’s another example:

let carColor = {
  best: "White",
  worst: "Gray",
};

let petColor = {
  best: "White",
  worst: "Gray",
};

let clothColor = {
  best: "White",
  worst: "Gray",
};

console.log(carColor);

// The invocation above will return:
{best: "White", worst: "Gray"};

Try it on StackBlitz

Notice that the snippet above contains three identical objects. However, storing each one in three unique namespaces helped avoid any collision between them.

Overview

This article discussed what a JavaScript namespace is. We also used some examples to illustrate how namespaces work.

Thanks for reading!

Similar Posts