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
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:
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
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
Notice that the snippet above contains three identical objects. However, storing each one in three unique namespaces helped avoid collisions.