Skip to content
Advertisement

Calling a Self-Executing Function from an Event Listener

Assume this is my only HTML

<input id="target" type="number">

And assume this is my only JavaScript

var target = document.getElementById('target');

I want to execute a function whenever the input changes, but I also want to execute said function once when the page is loaded (Self-Executing Function or IIFE). Below are 3 examples, 1 of which doesn’t work.



The following works as expected:

target.addEventListener('input', myFunction);

function myFunction(){
    console.log('executed!');
}
myFunction();

Here the function will be executed when the page is loaded. It will not be executed by the eventListener, instead it will log ReferenceError: myFunction is not defined to the console:

target.addEventListener('input', function(){
    myFunction();
});

(function myFunction(){
    console.log('executed!');
})();

This one will neither execute when the page is loaded, nor by the eventListener and will log ReferenceError: myFunction is not defined to the console:

target.addEventListener('input', myFunction);

(function myFunction(){
    console.log('executed!');
})();


My question: Why does the 3rd example not work?

Advertisement

Answer

The whole point of an IIFE is to prevent pollution of the Global (or higher) scope. It doesn’t work because an Immediately Invoked Function Expression (IIFE) is an anonymous function. So, when you set up your IIFE syntax with a name, the function name is ignored outside of the expression.

From MDN:

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.

Also, your second example actually does not work for the same reason. You do see your executed! message, but that is because the IIFE self-executes. If you proceed to change the input’s value, you will get the same error as option #3.

var target = document.getElementById('target');

target.addEventListener('input', function(){
    myFunction();
});

(function myFunction(){
    console.log('executed!');
})();
<input id="target" type="number">
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement