DEV Community

Discussion on: Everything you should know about Javascript functions

 
danielbokor profile image
Daniel Bokor

IIFE is just that - a function that is invoked right after its definition.

Closure is the way JavaScript (the engine and the scope manager) handles the scope of variables, i.e. it detects whether the execution context of the function that gets returned has a reference to a variable defined in its parent scope.
Even if the garbage collector should have taken care of the parent scope (i.e. remove the references from the memory), due to the fact that the returned function also has reference to the same variable, it "closes" upon that variable, thus we have a closure.

Given your first example (the one with placing an order), I wrote a small repl that exemplifies a non-IIFE function that takes advantage of closure.

repl.it/@danielbokor/closure-example

tl;dr any function may take advantage of closures within JS, not just the ones that are an IIFE

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
jlipinski3 profile image
Josh Lipinski • Edited

Fwiw the pattern of using iife's in js to call pseudo-methods without separately instantiating an object using "new" is so clean to me. I'm a huge fan of the revealing module pattern. Your pattern is interesting. One thing that drives me nuts is I've yet to find an es6 pattern that matches the revealing module pattern in terms of being self contained and simplistic. Module exports are wacky to me, having to create a new file for each "object" and exporting functions individually in order to namespace them. And static methods in a class dont have access to constructor properties. The revealing module pattern hit on all of this...And if I wanted to put a bunch of iife's in one file and make said functionality available globally - yet namespaced - I could. To me it's like we went backwards with these es6 imports...it's become more procedural. just a gripe.

Thread Thread
 
danielbokor profile image
Daniel Bokor

I agree with you, using the IIFE has a single execution context thus there is a single closure.

My point was that closure may exist without the need of using an IIFE.

Also, you are right: we both know how to use closure ;)