JavaScript LogoKeeping the global namespace clean is a good idea. Immediate functions allow the JavaScript programmer to do so with a great deal of power.

In a previous post, we discussed the topic of the JavaScript Immediate Function. Now let’s re-visit this topic with a focus on creating a private scope with which we can interact.

Most JavaScript programmers know that you can create an object, and then extend that object by simply assigning a new property to it. In fact, you can even do so at run time. Well, this is all very nice, but as you do so, these new properties are public. Which means, of course, that they are accessible to anyone and mutable at any time. So, while this can have it’s uses, there is a downside, because any line of code has access to these properties and can change them. Sometimes, that can get messy.

Example # 1

In Example # 1, we created a global variable named “foo”. We then added two properties to it: “name” and “say”. There is no reason why at a later point in our code, we couldn’t intentionally (or even worse, accidentally) do the following: = “marge”. If this is intentional, no problem, but if it is done by accident, it creates cases that become frustrating to debug and manage. So, obviously, what we need is a way to store values inside of foo that have a clearly defined interface for retrieval and mutation.

Example # 2

{ var _name = “bart”; var MyConstructor = function(){ this.getName = function(){ return _name; }; this.setName = function(newName){ _name = newName; }; } return new MyConstructor(); })(); console.log( foo.getName() ); console.log( foo.setName( “simpson” ) ); console.log( foo.getName() );

In Example # 2, we have drastically altered our global variable so that it is an immediate function. Inside of that immediate function, we have a private variable called “_name”. We return an instance of our constructor function, which allows us to use the “this” keyword to create privileged members. These two functions allow us to set, and get the value of name. If you paste Example # 2 in your JavaScript console, and run it, you will see that the value of our private variable “_name” changes over the course of the two “get” statements. This is because in between these two get statements, we use the “setName” method to change the value of that private variable.


The JavaScript immediate function can be used to create a global variable that has its own private scope. This is useful when creating functionality that requires storing data for the life of the page and managing access to that data.

Helpful links for Immediate Functions in JavaScript



One Comment

Comments are closed.