JavaScript Namespaces Overview

Namespace

Namespace will help in organizing the code and distinguishing the level of code. In other languages like C#, JavaScript does not provide a namespace by default, but we can create a namespace.

Syntax

var RK = RK || {};  
RK.myVariable = “Ramakrishna”;  

Advantages of the namespace

  • Organize the code.
  • If we have 2 more functions with the same name, we can differentiate using a namespace.
  • Easily recognize the variables and functions (if we have included several JS functions in the page, it will be challenging to identify the function from where it is coming, using Namespace, we can easily recognize the function where it is defined).

Namespace Sample

Below the sample, I have created a multilevel namespace; I will call the function using the Namespace.

MyCustomPage.js File

var RK = RK || {};  
RK.MyCustomPage = RK.MyCustomPage || {};  
  
RK.MyCustomPage.UserName = "Ramakrishna Basagalla";  
  
RK.MyCustomPage.AlertUserName = function () {  
   alert(RK.MyCustomPage.UserName);  
};  

MyCustomPage.html file

<!DOCTYPE html>  
<html>  
  
<head>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
    <script src="MyCustomPage.js"></script>  
</head>  
  
<body>  
    <h1>Javascript Namespace Sample</h1> // Calling JS function using namespace  
    <button onclick="RK.MyCustomPage.AlertUserName()">Alert User Name</button>  
</body>  
  
</html>  

Output

Run