Skip to content

Instantly share code, notes, and snippets.

@1isten
Last active January 3, 2022 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1isten/9161f3044c545a59aec2c974f96146a1 to your computer and use it in GitHub Desktop.
Save 1isten/9161f3044c545a59aec2c974f96146a1 to your computer and use it in GitHub Desktop.
JavaScript Closures made easy ;P

Three JS key concepts:

  1. Functions can be nested: a child function inside a parent function (and can be returned by the parent function).

  2. Lexical scope: variables from outter scope are available to inner functions (when these inner functions are created).

  3. Variables which can be accessed by any function anyhow will never be garbage collected (until that function is garbage collected).

A "closure" is a place (scope) where those variables are stored at and is only available for that function who needs to access them. Except for that function, there is no other API to access/modify those variables in the closure.

@1isten
Copy link
Author

1isten commented Mar 23, 2021

In chrome dev console we can "see" closures like:

closure-1

closure-2

@1isten
Copy link
Author

1isten commented Mar 23, 2021

Some people may call that returned function bar (and its [[Scopes]] as a whole) a closure. And that's ok.

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