Skip to main content

Namespace in JavaScript – Explained with Examples

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

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.

Let's see the syntax below.

Syntax

keyword namespace = object;

You can see that a namespace's syntax is the same as that of an initialized JavaScript variable.

Below are some examples.

Example 1: 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 2: Namespaced Functions

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. Therefore, we could indicate the specific myName function the computer should invoke.

Example 3: Namespaced Objects

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 collisions.

Overview

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

If you like this article, please Tweet it.

Thanks for reading!