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

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