(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
Copying what Ethan Brown says in Learning Javascript:
Function expressions allow us to create something called an immediately invoked function expression (IIFE). An IIFE declares a function and then runs it immediately. Now that we have a solid understanding of scope and closures, we have the tools we need to understand why we might want to do such a thing. An IIFE looks like this:
(function() {
// this is the IIFE body
})();
We create an anonymous function using a function expression, and then immediately call (invoke) that function. The advantage of the IIFE is that anything inside it has its own scope, and because it is a function, it can pass something out of the scope:
const message = (function() {
const secret = "I'm a secret!";
return `The secret is ${secret.length} characters long.`;
})();
console.log(message);
The variable secret is safe inside the scope of the IIFE, and can’t be accessed from outside. You can return anything you want from an IIFE, and it’s quite common to return arrays, objects, and functions. Consider a function that can report the number of times it’s been called in a way that can’t be tampered with:
const f = (function() {
let count = 0;
return function() {
return `I have been called ${++count} time(s).`;
}
})();
f(); // "I have been called 1 time(s)."
f(); // "I have been called 2 time(s)."
Because the variable count is safely ensconced in the IIFE, there’s no way to tamper with it: f will always have an accurate count of the number of times it’s been called. While block-scoped variables in ES6 have somewhat reduced the need for IIFEs, they are still quite commonly used, and are useful when you want to create a closure and return something out of it.