Monday, April 08, 2019

Simple Understanding on JavaScript namespace

To understand the concept of namespace in JavaScript, you might have gone through lengthy article which trying to correlate other aspect of JavaScript and OOPS concept to make or convince you to understand the Namespace in JavaScript topic.

Here I've corroborated few points on my own to understood this concept from various sources.


  1. This approach will useful for reusable and maintainable code base and also easy to roll out the new updates to it.
  2. Another valid point is it can be extensible without modifying the original JS file.
  3. Namespace approach has been widely used in almost all JS framework and libraries.
  4. It removes the variable name, class and function name pollution in the Web Page or Apps.
    Example:
If you have 3 functions in the page, called MapView(), but same time, you are using the third party library and not sure the variable names in the library, If you used the same name function or variable in your page, then it will be conflict.

To overcome this problem, just isolate the function name or variable name using the namespace.

You can declare the namespace in Javascript like this.its best idea to write the below code in separate JS.

var ns = {};
ns.login = function()
{
alert("You are logged in");
}
ns.logout=function()
{
alert("Logged out");
}


You can call this namespace in your html,


Namespace in JS - Simple understanding