Overview
JavaScript self-invoking functions (aka. Immediately invoked functions or IIFEs) are functions that run as soon as they are defined. They are useful when you need to create a function that will only be used once or to create a private scope to prevent naming conflicts.
Each self-invoking function contains 2 parts:
- The first part is the anonymous function with lexical scope enclosed within the grouping operator – a pair of parentheses (). This prevents accessing variables within the self-invoking function as well as reduces polluting the global scope.
- The second part is the immediately invoked function expression () that makes JavaScript execute the function immediately.
Defining Self-Invoking Functions
You can create a self-invoking function by using the arrow syntax like this:
(() => {
// some code
})();
If you want your function to do some asynchronous tasks, just add the async keyword like so:
( async () => {
// some code, use the "await" keyword as needed
})();
You can also declare a self-invoking function with the old-fashioned function keyword as follows:
(function () {
// some code
})();
Now, it’s time to see some real-world examples of using self-invoking functions.
Real-World Examples
Fetching Data
In this example, we will create an asynchronous self-invoking function that fetches some data from an API and log it to the console. This is useful when you need to get data as soon as a web page is loaded.
The code:
(async () => {
// Use try/catch to handle errors
try {
// Use the Fetch API to fetch data from an API endpoint
const response = await fetch(
'https://api.slingacademy.com/v1/sample-data/users/1'
);
// Parse the response as JSON
const data = await response.json();
// Log the data to the console
console.log(data);
} catch (error) {
// Log any error to the console
console.error(error);
}
})();
Output:
In this example, we will define a self-invoking function that performs some initialization code that set up an event listener on a button.
The code:
<!-- index.html -->
<html>
<head>
<title>Sling Academy</title>
</head>
<body>
<h1>Sling Academy</h1>
<button id="my-button">I am a button</button>
<!-- JavaScript code -->
<script>
(() => {
// Select the button element by its id
const button = document.getElementById("my-button");
// This function handles the click event on the buttonn
const handleClick = () => {
alert("You clicked me!");
};
// Add an event listener to the button element
button.addEventListener("click", handleClick);
})();
</script>
</body>
</html>
The result:
Drawbacks
Self-invoking functions have some drawbacks if a developer doesn’t use them carefully, such as:
- They can make debugging more difficult by hiding the function name from the stack trace.
- They can cause errors if they are not properly terminated with a semicolon before or after the function expression.
- They can create confusion and inconsistency with other function declarations and expressions.
Conclusion
You’ve learned what self-invoking functions are, why they are useful, and how to define them. You’ve also seen some practical examples that demonstrate some real-world use cases of this kind of function. Try to modify the sample code, remove some code lines, add some code lines on your own, and see what happens next. Happy coding!