Open In App

How to declare namespace in JavaScript ?

The coding standard of assigning scope to identifiers (names of types, functions, variables, and so on) to avoid conflicts between them is known as a namespace. It is a framework for a collection of identifiers, functions, and methods. It gives its contents a sense of direction so that they are easily distinguishable and ordered. In a program, for example, the same variable name may be needed in various places. In this case, using namespaces will isolate these settings, allowing the same identifier to be used in many namespaces.

You must have come across the term “namespace” a number of times. It prevents cluttering of the coding standard and keeps it cleaner by logically organizing the code and eliminating unexpected and predicted collisions. To do this, we must first build a namespace in the application and then use it. A namespace is a must-have because, in the end, we require third-party libraries and modules. However, the namespace is not accessible in JavaScript. But the good thing is that namespace can be conveniently created in JavaScript.



Syntax:

To initialize an empty namespace



var <namespace> = {};  

To access variables in the namespace

<namespace>.<identifier> 

By invoking a global object that includes both, variables and functions, the JavaScript Namespace feature may be duplicated. As various libraries are employed in current web apps, you should use a namespace to eliminate confusion in the code. The examples below will help you comprehend the topic more thoroughly.

Example:




<script>
    var website = {
        webName: function () {
            document.write("This website is called ");
        }
    }
    var webSite = {
        webName: function () {
            document.write("GeeksforGeeks");
        }
    }
    website.webName();
    webSite.webName();
</script>

Output:Advantages of Namespaces in JavaScript:

We’ve seen how the JavaScript Namespace may help us write more structured and trustworthy code in our regular programming. It can be used without contaminating the global namespace.  We can avoid code obscurity and reduce the likelihood of naming collisions by doing so.  Also, you’ve seen two forms of Namespacing, Static and Dynamic Name Spacing, with a few basic examples to help you understand. 

Article Tags :