DEV Community

Discussion on: ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?

Collapse
 
gmartigny profile image
Guillaume Martigny • Edited

Honestly, you should never use a function before its declaration (hoisting or not).

The first is indeed the "default" one. It just put a new function into the scope.

For the second, I see two tiny benefit:

  • You can assign a long and descriptive function name to a shorter variable name. That way, your debugger with put the long function name in stack trace and your code can play with a simpler version.
// Don't go too short neither
const fetch = function fetchAllUsersFromDataBase () { /* ... */ }
const filter = function keepOnlyActiveUsers () { /* ... */ }
return Promise.all([fetch, filter]);
  • You can use the non-scoping property or arrow function. Using this inside an arrow function refer to the wrapping scope.
this.prop = 0;
const action = () => { this.prop++ };
for (let i = 0; i < 5; ++i) action();

Finally, IIFE don't declare a new function. That's indeed just a way to do "private" scoping.

const measure = (function () {
  const cache = {}
  return function measureTextLength (text) {
    if (cache[text]) return cache[text];
    const result = timeConsumingFunction();
    cache[text] = result;
    return result;
  }
})();