Wednesday, April 26, 2017

Immediately Invoked Function Expressions (IIFE) aka Self-executing Anonymous Functions

In the following html page, a heading shown. The color of the heading is changed to red by JavaScript. The scope of elem variable is global. If there is another global variable by the same name in any JavaScript included on this page, the elem will be destroyed and the script is not going to change the color of heading to red.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>IIFE</title>
</head>
<body>
<h1 id="heading">IIFE</h1>

<script>
var elem = document.getElementById("heading");
elem.style.color = "red";
</script>
</body>
</html>

In JavaScript, variables are either scoped globally (like above) or at function level. By wrapping the JavaScript on a page in an Immediately Invoked Function Expression (IIFE) (aka Self-executing Anonymous Function), we can limit the scope of elem variable to the function and avoid a name collision with an identically named variable in the global scope.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>IIFE</title>
</head>
<body>
<h1 id="heading">IIFE</h1>

<script>
(function (color){
var elem = document.getElementById("heading");
elem.style.color = color;
})("red");
</script>
</body>
</html>