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?
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:
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.