Introduction

Kenneth Truyers

JavaScript: Private variables

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:

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.