IIFE & its power !!

Prangshu Gogoi
2 min readJul 9, 2021

--

Photo by Claudio Schwarz on Unsplash

IIFE (Immediately Invoked Function Expression) also known as Self-Executing Anonymous Function is basically a way to execute javascript functions as soon as it is declared .

(function(){
//code that needs to be executed immediately
})()
//Explicit call of function not required

In order to make the lines inside IIFE block work, we need to pass an object to it , something in the below fashion :-

//Object to be worked on
const employeeDetails = {name: "John", city: "NY" , salary: 'xxx'}
// injecting employeeDetails to it
(function(){
// The object 'employeeDetails' is now available here
})(employeeDetails)

Lets understand one of the ES6 feature called destructing at the first place before proceeding to IIFE working:-

// Defining an object with certain properties
const employeeDetails = {name: "John", city: "NY" , salary: 'xxx'}
/* To extract out only few properties we have to use the same property names as variables.
* Extract multiple properties regardless of their order.
*/

const {city, name} = employeeDetails
console.log(city) //NY
console.log(name) //John

Coming back to the IIFE working combined with ES6 destructing

//Object to be worked on
const employeeDetails = {name: "John", city: "NY" , salary: 'xxx'}
// injecting employeeDetails to it
console.log((function({ name, city}){
return { name: name, city: city }
})(employeeDetails))

Bringing in ES6 arrow functions to picture, the code can be concise to …

//Object to be worked on
const employeeDetails = {name: "John", city: "NY" , salary: 'xxx'}
// injecting employeeDetails to it
console.log((({ name, city})=>{
return { name: name, city: city }
})(employeeDetails)) //{ name: "John", city: "NY" }
/* Or with a one liner return statement &
*
with ES6/ES2015, if you want to define an object who's keys have the same name as the variables passed-in as properties, you can use the shorthand and simply pass the key name.
*/
console.log((({ name, city})=>({name, city}))(employeeDetails))
//{ name: "John", city: "NY" }

JS is ❤ !!

--

--

Prangshu Gogoi
Prangshu Gogoi

Written by Prangshu Gogoi

A passionate MERN stack developer. Tech Coach !

Responses (1)