JavaScript: Private variables

The first thing you often hear when talking about JavaScript is often “JavaScript doesn’t have visibility modifiers, hence it doesn’t support private variables”. This is only valid for 50%, because JavaScript indeed doesn’t have visibility modifiers (public, private, friend) but it has closures and function scopes. With these tools we can make variables private. Let’s take the following function:

var names = ["Kenneth", "John", "Marc", "Robert"];

var lookup = function (index) {
    return names[index];
}

alert(lookup(0));

As you can see the variable “names” is public (and global) and can be accessed by any code running. A first thing that we can do is simply put the array in the function:

var lookup = function (index) {
    var names = ["Kenneth", "John", "Marc", "Robert"];
    return names[index];
}

alert(lookup(0));

This is of course not very optimal because it will reinitialize the Array every time we execute the function.

What you can do is use the fact that functions are first class objects and use a closure:

var lookup = (function () {
    var names = ["Kenneth", "John", "Marc", "Robert"];
    return function (index) {
        return names[index];
    };
} ());

alert(lookup(0));

In this last example we declare a function and execute it immediately (the outer function). This function declares first the Array (and thereby the scope is confined to that function). After that it returns a function that looks up the index in the Array.

Now we have defined the Array only once (while executing the outer function), but because the function that looks up the value in the Array is contained within the same scope as he outer function, the Array will still be available when the function is called.

This is only one of the many advantages that closures in JavaScript give you. It’s really a very good and powerful part of the language. Understanding this completely can be tricky, but once you get it, you’ll start to see the beauty of JavaScript.

Comments are closed.