1

Whats The point of Immediately Invokable Function Expressions? it literally does the same thing a function does.. what is the point and the difference?

  • 1
    Line 2 from the [Wikipedia page](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression): _Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function._ – 001 Dec 16 '18 at 00:03

1 Answers1

2

They are typically used to control how variables are scoped or to take advantage of closures. For example this doesn't require a global counter variable to be in scope. c is private to the function. So in this case, it's not doing the same thing as a plain function — you wouldn't be able to do this with a plain function unless you depended on variable external to the function, which could be altered outside the function.

let counter = (function() {
  let c = 0
  return function() {
    return c++
  }
})()

console.log(counter())
console.log(counter())
console.log(counter())
Mark
  • 90,562
  • 7
  • 108
  • 148