Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

Creating namespaces in JavaScript

Daniel Gheorghe Difficulty: 35 / 50 Tweet

This article is old. Be careful! It might contain outdated information.
Here's an alternate resource that I am recommending for this topic.

pins inside container

In this tutorial I will show you how I write my JavaScript code by creating a namespace and holding all my code inside its scope. I am not saying that this is the best method to do it, but I'm sure that it's much better than writing code in the global scope.

I always find that it's much easier to learn about new coding techniques through real life examples than just reading pages of theory. So the to do list for today is to develop a JavaScript application that logs all the books in a library. As I said you will be creating your own namespace and all the code will reside in that namespace.

The bad way to do it

  
    var books = ['Introduction to JavaScript', 'Javascript Namespaces', 'Advanced web development principles'];
    function loadData(data)
    {
      var i;
      for(i in data)
      {
        console.log(data[i]);
      }
    }
  

Does the code above look familiar ? It probably does because it's how most developers write their JavaScript. Why is this a bad coding technique ?

  • The global namespace is now polluted with a function called loadData. This means that as you add more scripts to your code you have to be careful to not use that function name again.
  • The books array is loaded into memory and it will never be cleared from it unless you delete it yourself.

How I would do it

First thing you need to do is to define an expression that will automatically invoke / call a function that holds all the code. These expressions are referred to as 'Immediately-Invoked Function Expressions'.Don't be scared by this (I was at first)!

Writing such an expression is equivalent to creating a new instance for an object. Because you will not be using multiple instances of the namespace, it makes sense to only call it once. The syntax for creating such an expression varies but the most common way I've seen this done is like this: (function(parameter){ /* your code here */ })(parameter); .

  
    (function ( myLibrary ) {
        var books = ['Introduction to JavaScript', 'Javascript Namespaces', 'Advanced web development principles'];

        myLibrary.loadData = function()
        {
          var i;
          for(i in books)
          {
            console.log(books[i]);
          }
          return true;
        };
    })(window.myLibrary = window.myLibrary || {});

    console.log(myLibrary.loadData());
  

The reason why the function definition receives the namespace as a parameter is because you will need to be able to modify it inside the function. Also, window.myLibrary = window.myLibrary || {} is necessary because you need to check if the namespace is actually defined inside the global scope.

Properties and methods defined inside the 'Immediately-Invoked Function' are private by default unless you define them as part of the namespace like this: namespace.your_property = 'value';. Because the 'books' variable is private you can't access it from outside the 'Immediately-Invoked Function' scope unless there's a public method inside the namespace that accesses it (in our case, the loadData method).

Hope you enjoyed this tutorial. If you think there are better ways to achieve this let me know through the comments section below.

comments powered by Disqus