Invoke Function Immediately in JavaScript

Introduction

 
In this article, we will learn how to invoke a function immediately in JavaScript. The beauty of immediately an invoked function is that, when the page loads, the function will execute, there is no need to call the function explicitly. In this article, we will try to understand the implementation of an immediately invoked function. 
  1. <!DOCTYPE html>    
  2. <html xmlns="http://www.w3.org/1999/xhtml">    
  3. <head>    
  4. </head>    
  5. <body>    
  6.     <form id="form1" runat="server">    
  7.         <script>    
  8.                 
  9.             (function () {    
  10.                 console.log('Immediately invoked function');    
  11.             })();    
  12.                 
  13.         </script>    
  14.     </form>    
  15. </body>    
  16. </html>   
 
 
More than one immediately invoked function
  1. <!DOCTYPE html>    
  2. <html xmlns="http://www.w3.org/1999/xhtml">    
  3. <head>    
  4. </head>    
  5. <body>    
  6. <form id="form1" runat="server">    
  7.         <script>    
  8.                 
  9.             (function () {    
  10.                 console.log('first function');    
  11.             })();    
  12.      
  13.             (function () {    
  14.                 console.log('second function');    
  15.             })();    
  16.                 
  17.         </script>    
  18.     </form>    
  19. </body>    
  20. </html>   
     
     
    Pass value to immediately invoked function
    1. <!DOCTYPE html>    
    2. <html xmlns="http://www.w3.org/1999/xhtml">    
    3. <head>    
    4. </head>    
    5. <body>    
    6.    <form id="form1" runat="server">    
    7.         <script>    
    8.             (function (name) {    
    9.                 console.log('name is:- ' + name);    
    10.             })('Sagar pulidindi');    
    11.         </script>    
    12.     </form>    
    13. </body>    
    14. </html>   
     
     

    Summary

     
    In this article, we learned the concept of immediately invoked functions in JavaScript. I hope you have understood the concept. In future articles, we will learn a few more concepts of JavaScript. 


    Similar Articles