Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
namespace
communitycreator

What are the namespace fundamentals in JavaScript?

Saad Akbar

Namespace of a language defines the paradigm of a programming language. It mostly consists of variable types, names of functions, and the scope of the data. The following list contains the fundamentals of a namespace in JavaScript:

1. Single global variable

A single global variable means that we can initialise the variable as a global variable and can use it anywhere in the application.

var globalVariable =  (function(){
        function(){
            /*...*/
        },
        return{
            /*...*/
        }
})();

2. Object literal notion

We can also define functions in an object by using the key value pairing. For example:

var variable = {
    variableFunction:function(){ /**/ },
    firstObject : {},
    key : {
        values : {}
    },
};

3. Nested namespacing

Nested namespacing is commonly used to identify similar namespaces uniquely. For example:

educative["webpages"] = educative["webpages"] || {};
educative["links"] = educative["links"] || {};

Here, educative is the same variable, but has different named indexes.

4. Immediately-invoked function expressions (IIFEs)

An IIFE is useful to protect anything from global namespacing. It is useful to encapsulate the function and variables along with its data. It allows the function to be invoked as soon as it is declared. For example:

var namespace = namespace || {};
(function( parameter ){
    parameter.fun = "fun";
    parameter.fun2 = function() 
    {
        return "fun";
    }; //self invoking function
})(namespace);

RELATED TAGS

javascript
namespace
communitycreator
RELATED COURSES

View all Courses

Keep Exploring