An IIFE (Immediately Invoked Function Expression) in JavaScript is a function that is defined and executed immediately after its creation. It is often used to create a private scope for variables and avoid polluting the global scope.
Here's an example of an IIFE:
(function() {
// Code inside the IIFE
var x = 10;
console.log("Inside IIFE: x =", x);
})();
// x is not accessible outside the IIFE
// console.log("Outside IIFE: x =", x); // Uncommenting this line will result in an error
In the above example:
- We define an anonymous function using `(function() { ... })`.
- The function is immediately invoked with `()` right after its definition.
- The variable `x` is scoped only within the IIFE and is not accessible outside of it.
Another example of an IIFE:
// named IIFE
(function chai() {
console.log("DB Connected");
})();
// unnamed IIFE
( () => {
console.log('DB Connected two');
} )();
// IIFE with parameters passed
( (database) => {
console.log(`DB connected is ${database}`);
} )('MONGODB');