Sling Academy
Home/JavaScript/JavaScript Self-Invoking Functions: Tutorial & Examples

JavaScript Self-Invoking Functions: Tutorial & Examples

Last updated: March 23, 2023

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:

Setting up an event listener on a button

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!

Next Article: JavaScript: Define a Function with Default Parameters

Previous Article: How to use the for…of loop in JavaScript (best practices)

Series: Mastering Control Flow in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration