Skip to content
Akin C edited this page Apr 15, 2018 · 10 revisions

Welcome to the Javascript-IFFE-and-local-scopes- wiki!

This repository is part of a larger project!

◀️ PREVIOUS PROJECT| NEXT PROJECT ▶️


IIFE stands for Immediately-invoked Function Expression.

To understand what it means in javascript code level, here follows an example:

//Anonymous function
(function(anyVariable)
{

    anyVariable += anyVariable;
    console.log(anyVariable);//Outputs number value 84

})(42);//42 is the value which will be given "anyVariable"

The ananymous function will be called immediately by the last two curved brackets. In the listing above, the value 42 is given to the argument anyVariable. The curved brackets which encase the function, it seems, are needed to prevent any possible parse errors and to improve readability.

Javascript does not support namespaces in which a programmer could be allowed to seperate different codeblocks, but it does have scopes. Javascript´s variables are function-scoped(this should also explain the point with local scopes) and in this the IFFE finds its use. A following code example shall explain it:

function anyFunction(oldList)
{
    var newList = [];

    for(var i = oldList.length; i >= 0; i--)
    {
        newList[i] = function()
        {
	    console.log(i);//Outputs "-1"
            return oldList[i];
        };
    }

    return newList;
}

//A list which is needed for "anyFunction"
numList = [10,20,30];

//Same as: "anyFunction(numList)[0]();" 
var myList = anyFunction(numList);
var aNumber = myList[0];

console.log(aNumber());//Outputs "undefined"

To understand the second listing, it is important to understand variable hoisting. The Coder could think that anyFunction reorganizes any List and gives an access with myList[0]. This is not the case! The value is undefined because variable i has at that time the value -1.

Such situation should be solvable with IFFE and in the file "iffe.js" a solution is presented.

Content

The user interaction part should look like the content as seen below by starting "index.html" in a web browser.

ERROR: No image found!

Note that all files should be placed in the same folder so that the functionality of the code is guaranteed.

Clone this wiki locally