DEV Community

Cover image for Enough JavaScript to get you Started : #19 IIFEโœจ
Adarsh Pandya
Adarsh Pandya

Posted on

Enough JavaScript to get you Started : #19 IIFEโœจ

IIFE โœจ

๐Ÿ‘‰ IIFE or immediately invoked functions as expressions simply refers to a function which runs as soon as it is defined.

๐Ÿ‘‰ Which means if you have to write a function which runs in beginning of your web app , you can use IIFE.

๐Ÿ‘‰ in early days if we want to do something like this we need to define a function and call it...

๐Ÿ‘‰ but with IIFE design pattern the syntax and the code makes much more sense.

๐Ÿ‘‰ IIFE takes 2 parentheses , one is meant for defining a anonymous function and another is meant to call the anonymous function.

๐Ÿ‘‰ Syntax

(
  // anonymous function
  function () {
    //function body
})();
Enter fullscreen mode Exit fullscreen mode


๐Ÿ‘‰ We'll create one IIFE which will greet user as soon as he/she comes to our website ๐Ÿ˜€

๐Ÿ‘‰ Example : the old way
function greet () {
    alert('hello user ! how are you?');
}

greet();
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Example : the new way

(function(){
    alert('hello user ! how are you?');
})();
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Example : Arrow functions as IIFE

( () => {
      alert('hello user ! how are you?');
})();
Enter fullscreen mode Exit fullscreen mode

Let me know in comment section if you have any doubt or feedback. it's always worth to give time to the thriving developer community :)

Keep Coding โค

Hey , Let' Connect๐Ÿ‘‹

Twitter /
Github

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Nicely explained.