JavaScript Namespaces Overview

Namespace

Namespace will helps in organizing the code and distinguish the level of code.

In other language like C#, JavaScript does not provide namespace by default, but we can create namespace.

Syntax:

  1. var RK = RK || {};  
  2. RK.myVariable = “Ramakrishna”;  
Advantages of namespace:

  • Organize the code.

  • If we have 2 more number of function with the same name, we can differentiate using namespace.

  • Easily recognize the variables, functions (if we have included several JS functions in page, it will be difficult to identify the function from where it is coming, using Namespace we can easily recognize the function where it is defined).

Namespace Sample

Below sample I have created multilevel namespace, I am going to call the function using the Namespace.

MyCustomPage.js File

  1. var RK = RK || {};  
  2. RK.MyCustomPage = RK.MyCustomPage || {};  
  3.   
  4. RK.MyCustomPage.UserName = "Ramakrishna Basagalla";  
  5.   
  6. RK.MyCustomPage.AlertUserName = function () {  
  7.    alert(RK.MyCustomPage.UserName);  
  8. };  
MyCustomPage.html file
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  6.     <script src="MyCustomPage.js"></script>  
  7. </head>  
  8.   
  9. <body>  
  10.     <h1>Javascript Namespace Sample</h1> // Calling JS function using namespace  
  11.     <button onclick="RK.MyCustomPage.AlertUserName()">Alert User Name</button>  
  12. </body>  
  13.   
  14. </html>  
Output

Run

Ebook Download
View all
Learn
View all