Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active September 4, 2018 06:44
Show Gist options
  • Save rauschma/6d96de5478efad9865701d3605843356 to your computer and use it in GitHub Desktop.
Save rauschma/6d96de5478efad9865701d3605843356 to your computer and use it in GitHub Desktop.

The scope of a variable is the region of the program in which you can directly access the variable:

if (true) {
  let x = 123;
}

Here, the scope of x is the then-block of this if-then-else statement.

A closure is a function plus the connection to the variables that existed at its birth place:

function funcFactory(value) {
  return function () {
    return value;
  };
}

const func = funcFactory('abc');
func(); // 'abc'
func(); // 'abc'

funcFactory returns a closure. Because the closure still has the connection to the variables at its birth place, it can still access the variable value (even though it escaped its scope).

@ducin
Copy link

ducin commented Feb 11, 2018

extending a little bit on that, the inner functions have access to their local variables and variables of all enclosing scopes (inner functions have broader access than outer functions). JS keeps track on which scope does a given variable come from (that's where shadowing kicks in). This is also reflected in devtools/debugger:
image
(the breakpoint is set at return value; line)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment