Closure, and how do I understand it

Here is a code snippet I found in YDKJS.

function foo(){
  var a = 2;
  function baz(){console.log(a);}


function bar(fn){
  fn(); //closure happened

Can I say that because function baz got executed outside of its own scope, therefore closure happened?

I used to think that closure means in js , the inner functions have access of outer functions variables. But that is wrong. That’s what called lexical scoping.

If let’s say that during an interview I got asked: “could you tell me about closure in js and how it works?” can I show them this example snippet?

MDN to the rescue!

So as it says on that page, closure is a combination of the function and the lexical scope. Read that article. Please. :slight_smile:

snowmonkey already gave you a good resource.

One easy way to think about closures is that whatever is declared in your function will still have access to its scope even after the function executes. In other words, the scope is retained even after the function has executed.

1 Like