JavaScript Namespaces Overview


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.


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 () {  

MyCustomPage.html file

<!DOCTYPE html>  
    <script src=""></script>  
    <script src="MyCustomPage.js"></script>  
    <h1>Javascript Namespace Sample</h1> // Calling JS function using namespace  
    <button onclick="RK.MyCustomPage.AlertUserName()">Alert User Name</button>