DEV Community

horiyorrmi72
horiyorrmi72

Posted on

function of function & closure

A "function within a function" and a "closure" are related concepts, but they have distinct differences:

  1. Function within a Function:

    • This refers to a function that is defined inside another function.
    • The inner function can access variables and parameters of the outer function, but it does not necessarily create a closure.
    • The inner function can be invoked only within the scope of the outer function.
    • Once the outer function finishes executing, the inner function's access to the outer variables may be lost.
  2. Closure:

    • A closure is created when an inner function "closes over" its surrounding lexical (scope) environment, capturing and retaining access to variables even after the outer function has finished executing.
    • Closures allow the inner function to access and "remember" the variables of its outer function, even outside the outer function's scope.
    • Closures are not limited to being invoked only within the scope of the outer function; they can be passed around and invoked from different places, preserving access to the captured variables.

every closure is an example of a function within a function, but not every function within a function creates a closure. A closure specifically occurs when an inner function maintains access to its enclosing scope, allowing it to access variables from the outer function even after that function has completed its execution.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

A closure is NOT a function. EVERY function has an associated closure, regardless of whether it was created inside another function.