How do I declare a namespace in JavaScript?


A namespace is a programming concept that gives identifiers (names of types, functions, variables, etc.) scope to avoid name conflicts. For instance, a program may need to use the same variable name in many contexts. In such a case, namespaces will separate these contexts so that the same identifier may be utilized in many namespaces.

The initialization and application of namespaces in JavaScript will be covered in this tutorial. A namespace is not by default available in JavaScript. Constructing a global object that contains all functions and variables, the JavaScript Namespace feature may be repeated. Because numerous libraries and components are utilized in contemporary online applications, namespace should be used to prevent misunderstanding in the code.

Namespace with Object Literal Notation

In this approach, we will use the Object Literal Notation.

In the Object Literal Notation, JavaScript namespaces can only be specified once, and only within that namespace may function be written.

With a colon between each pair of keys and values, this may be compared to an object with a collection of key-value pairs, where keys can also stand in for new namespaces.

The benefit of object literals is that they help properly organize code and arguments while not contaminating the global namespace.

They are quite helpful if you want to design structures that can be extended to enable deep layering and are easily readable.

Contrary to simple global variables, object literals frequently additionally consider checks for the presence of a variable with the same name, considerably lowering the likelihood of a collision.

Syntax

Initializing an empty Namespace is the first step −

Var <namespace> = { };

The namespace's variables can then be accessed by using −

<namespace>.<identifier>

Approach

  • We create an object named "student" and then declared two functions getStudentName() and getStudentAddress() inside those.

  • Inside the getStudentName() function we have a variable that is initialized to the name of the student and returns that.

  • Inside the getStudentAddress() function we have a variable that is initialized to the address of the student and returns that.

  • Outside the object, we call these functions, and similarly each value is printed.

  • In this way, studentName and studentAddress are namespaced under student: student.getStudentName() and student.getstudentAddress().

Example

In the below example, we have used the Object Literal Notation to declare a namespace in JavaScript.

<html>
<head>
   <title> JavaScript Namespace </title>
</head>
<body>
   <h2> Namespace with Object Literal Notation </h2>
   <script>
      var student = {
         getStudentName: function() {
            var studentName = "Vivek Kumar lives in ";
            return studentName;
         },
         getstudentAddress: function() {
            var studentAddress = "Kota, India";
            return studentAddress;
         }
      };
      document.write(student.getStudentName());
      document.write(student.getstudentAddress());
   </script>
</body>
</html>

In the above output, users can observe that the student’s name and Address when referenced are printed.

Namespace with Argument

In this approach, we will see a namespace declaration with an argument. Using a function wrapper that returns an object that represents a module's public interface, a namespace enables its functionality to be contained inside the global scope. Calls the function right away and assigns the output to a namespace variable. Dynamic namespacing, commonly referred to as namespace injection, applies to this namespace. It is symbolized by a proxy that is specifically referred to inside the function wrapper. Here, we'll give self-invoking functions the namespace parameter.


Syntax

Let us see the example below to understand this method better.


var <name> = {};
(function(variable) {
   <name>.variable= function() {
   var x = "ABCD";
   return x;
};

Approach

  • We create an object named student. Here we use a namespace as professor declared inside the function.

  • We then have three functions getStudentName(), getStudentAddress() & getStudentLOB() declared inside it.

  • Inside the getStudentName() function we have a variable that is initialized to the name of the student and returns that.

  • In the getStudentAddress() function we have a variable that is initialized to the address of the student and returns that.

  • In the getStudentLOB() function we are initializing the company the student works for.

  • As we close the function, the object student is referenced. Outside the object, we call these functions, and similarly, each value is printed.

  • In this way, name, LOB and address are namespaced under student: student.getStudentName(),student.getstudentAddress() and student.getstudentLOB().

Example

The example below demonstrates the JavaScript Namespace concept using a namespace as an argument.

<html>
<head>
   <title> JavaScript Namespace </title>
</head>
<body>
   <h1>Namespace as argument </h1>
   <script>
      var student = {};
      (function(professor) {
         professor.getStudentName = function() {
            var name = "Milind living in ";
            return name;
         };
         professor.getStudentAddress = function() {
            var address = "Mumbai, India works with ";
            return address;
         };
         professor.getstudentLOB = function() {
            var LOB = "Microsoft";
            return LOB;
         }
      })(student);
      document.write(student.getStudentName());
      document.write(student.getStudentAddress());
      document.write(student.getstudentLOB());
   </script>
</body>
</html>

Users can observe that the namespace was supplied as an argument. The name, address, and LOB are accessed from outside the object and printed.

Conclusion

We have learned the two methods of how to declare a namespace in JavaScript. The first method is the Object Literal Notation, and the second is when we can supply a namespace as an argument. In JavaScript, isolation, and protection from other JavaScript code when working on web applications are provided by the JavaScript namespace. The identical variables that we might not be conscious of are "overwritten" while expressing a namespace.

JavaScript code that uses namespaces is better organized, and simpler to read, comprehend, and adapt as necessary. The script of the web page should be maintained above the page HTML since we are utilizing namespace functions and definitions, ensuring that any references and objects produced are instantly accessible when the page loads. Usage of Namespaces in any application enhances the readily of the code and helps in debugging easily.

Updated on: 22-Jul-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements