Code

“I’ve finally learned what ‘upward compatible’ means. It means we get to keep all our old mistakes.”

— Dennie van Tassel

JavaScript Immediately Run Functions

Immediately run functions (IRF) provide a mechanism in JavaScript to encapsulate an environment and protect it from external tinkering. One obvious benefit is that you’re able to create private variables and functions by controlling the environment your code runs in.

Baseline example

Here is a simple example which declares the variable answer and assigns it the value 42. Then, the example alerts a dynamic statement made from the String "The answer is " and the current value of answer. Go ahead and run this example now to see the alert.

<script type="text/javascript">
var answer = 42;
function ex0() {
  alert("The answer is " + answer);
}
</script>

Run Example

Now let’s try and mutate the value of answer. We’ll use the Firebug plugin for Firefox here, but this will also work using similar tools for Safari, Chrome and Internet Explorer.

Open Firebug now and click on the “DOM” tab as highlighted in the image below. Next, scroll though the list looking for the variable answer. Finally, scan over to the second column and edit the value by double-clicking it and changing it to something else. After you’ve completed those steps try running this example again to see the alert message display a different statement than before.

See how to protect this variable after the break

 Scroll to top