Organize Code

Namespace

JavaScript

 

Defining Namespace: Literal Object

ECMAScript 5
var circle = {
  PI: 3.14,
  
  area: function(r) {
    return r * r * circle.PI;
  }
}

console.log(circle.area(1));  // 3.14

Namespaces are used to avoid conflicting definitions and introduce more flexibility and organization in the codebase.

There are no special keywords for defining Namespaces in JavaScript, But there are ways to mimic them.

One easy way is to use JavaScript Object Literal Syntax.

 

Defining Namespace: Closure

ECMAScript 5
/* 
  Assume that window is a global object and
  the root of your namespace
*/
var window = window || {};

(function(circle){
  circle.PI = 3.14;
  
  circle.area = function(r) {
    return r * r * circle.PI;
  }
})(window.circle = window.circle || {});

console.log(window.circle.area(1)); // 3.14

You can namespace your code using closures.

Although this syntax is a little more complex to read, but it gives you more flexiblility and control over visibility of your variables and objects inside your namespace.