Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is every function in JS a closure [duplicate]

Tags:

I have been reading a fair bit about closures in JS. I have been through various guides as this one https://medium.freecodecamp.org/javascript-closures-simplified-d0d23fa06ba4

I still have one question though. Does a closure only refere to first order function (function returning a function). Or, is any function a closure ? The only difference I see really is like with some function not nested, one of the 3 scope chain (outer function's scope) would be empty still it doesn't exist.

like image 340
Scipion Avatar asked Apr 04 '19 13:04

Scipion


1 Answers

A closure is created by calling a function; the function itself isn't the closure. Conceptually, every function call implicitly causes a new closure to come into existence. For some functions, the closure is ephemeral and just vanishes as soon as the function returns:

function add2(n) {
  return n + 2;
}

That function returns only a number; nothing can refer to anything in the closure created by the function call, so the closure goes away and all you have left is the return value.

The closure becomes interesting when a function returns something that has one or more "hooks" into the local environment created when the function was called. (The function can expose the closure by modifying the global environment too.) So this function:

function addn(addend) {
  return function(n) {
    return n + addend;
  }
}

exposes the closure because the returned function has a reference to the parameter of the outer function.

I can't think of a way an ordinary function can expose a closure that doesn't somehow involve one or more functions that reference stuff from the local context (parameters, variables). (Generator functions are interesting, because yield kind-of always returns something that exposes the closure, I suppose.)

like image 72
Pointy Avatar answered Sep 22 '22 05:09

Pointy