Why my function is wrapped in parenthesis ?!

May 17, 2020


Javascript functions wrapped in parenthesis like in the example below are called Immediately Invoked Function Expression aka IIFE :

(function (){

    // calculating very important stuff


Here you can keep the function anonymous because no one is going to invoke it, but itself. You can also name it, this not will affect the โ€œself callโ€ behavior.

When should you use it ?

The main reason is scope visibility. For example, wrapping entire javascript file in a immediately invoke function it prevents to access variables defined outside that file: very helpful when you include a lot of js files ! If you come from the backend world you can consider it a way of defining the namespace.


Immediately Invoked Function Expressions:

  • They will keep your variables isolated
  • They avoid variables collision
    ( maybe from a different file which it was not wrapped in an IIFE ๐Ÿ˜†)

For further details check the official mozilla glossary.

Pingu ๐Ÿง

Written by Pingu who lives and works in Genoa building useful modern applications.

Something to share ?