Javascript IIFE: A beginner's guide

Javascript IIFE: A beginner's guide

What are IIFEs

IIFE stands for Immediately Invoked Function Expression. These are functions that are called and executed as soon as they are created.

Pronunciation

I don't know how you read it..I.I.F.E or iify or iife..it's all up to you, there is no standard way of pronouncing it. iify is however the most commonly used pronunciation.

Syntax

Parts of an IIFE.

IIFEs have two parts; the first part carries the function, the second part(the second pair of parantheses) calls the function and executes it.

Why use IIFEs

  1. IIFEs declare a variable and isolate it; the variable is not accessible outside the IIFE.
  2. IIFEs prevent pollution of the global scope. How? IIFEs isolate variables hence variables and functions within an IIFE will not affect variables without the IIFE even though they have the same name.
  3. IIFEs keep javascript code net and easy to maintain.

More fun facts on IIFEs

  • Variables can be assigned to an IIFE. The variables value is the return value of the IIFE
  • It's possible to use arrow functions as IIFEs.
  • Arguments can be passed to an IIFE
  • IIFEs can also be named just like regular functions

That's it for now with IIFEs. Thank you for reading this far!