logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

Namespaces

Earlier in the course we talked about variable scope and we saw that global variables can be accessed from anywhere in the code.

As our application grows and becomes more complex, it is likely that at some point two variables or functions will end up having the same name, resulting in conflict.

To avoid this we can make use of namespaces, which will create a local scope for our variables and functions. Javascript doesn't actually have namespaces like other programming languages, so what we'll see here are alternative ways of achieving the same outcome. The most common way of simulating namespaces is via objects.

Namespaces with objects

                    

    var bestSellersSlider = {};
    
    bestSellersSlider.products = ['product 1', 'product 2', 'product 3'];
    bestSellersSlider.interval = 3000;
    bestSellersSlider.infinite = true;
    
    bestSellersSlider.get_products = function() {
        console.log(this.products);
    };

    bestSellersSlider.get_products(); 
    // We can use the keyword this inside objects to refer to its properties and methods.


                    
                

Note that the names "products" or "interval" are generic names that could easily be repeated many times in a large web application. Instead of adding more words to our variables, like "productsOfBestSellersSlider", and making them separate in the global scope we place them inside an object that will hold all information about our slider.

Not only our code is now more organized but we can use simple and meaningful names like "products" without the risk of having a conflict with other variables throughout the code.

Instead of creating an empty object and adding properties later, we can also create everything we need when defining it:

                    

    var bestSellersSlider = {
        
        products: ['product 1', 'product 2', 'product 3'],
        
        interval: 3000,
        
        infinite: true,
    
        get_products: function() {
            console.log(this.products);
        }

    };

    bestSellersSlider.get_products();


                    
                

There are other ways of simulating namespaces in Javascript, like using functions and module patterns. You can also find more examples here.

Contents