0

If we define a function

(function(){ 
  console.log("");
})();

then it is invoked immediately. We could define the same function

function foo(){ 
  console.log("");
}
foo();

I fail to see a good use case for this, but if there is one, then I don't see why we not just define a normal function and call it. Why should we use immediately invoked functions and what are their advantages?

burkow
  • 17
  • 7
  • When you don't want to pollute the global namespace. When you want to perform asynchronous operations in an `async` function. – Pointy Feb 20 '22 at 17:50
  • For example: Scope, allowing to use `return`, invoking an `async` code part from synchronous code ... – CherryDT Feb 20 '22 at 17:50
  • IIFEs follow from the grammar of the language. Functions are first-class citizens. Expressions can thus return functions. Since functions are first-class and there is no type-safety, any value can be treated as a function to execute it by adding `()` at the end. Ergo, `(expression)()` is a valid construct in JavaScript. Similar to (expression) + 2` which is also allowed. It's not in any way a special feature that was added. It does have certain uses but nobody is mandating you use IIFEs. If you don't have a useful case for them, then don't. – VLAZ Feb 20 '22 at 17:56

0 Answers0