WTF is a Javascript Closure?

Christopher Agnus 🐟
Zero to Code
Published in
1 min readOct 24, 2018
“silver iMac with keyboard and trackpad inside room” by Carl Heyerdahl on Unsplash

In Javascript, you can nest a function within a function. The nested inner function is private to the containing (outer) function. This forms a closure.

A closure is an expression (typically a function) that has access to the outer function’s variables’ scope chain. The closure has three scope chains: its own scope, it has access to the outer function’s variable and has access to the global variables.

  • The inner function can only be accessed only from statements in the outer function.
  • The inner function forms a closure: the inner function can use arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function. ie. the inner function is private to the outer function.

The following example shows nested functions:

The inner function function inside(y) forms a closure that can call the outer function function outside(x) and specify arguments x,y for both the outer and inner function:

--

--

Christopher Agnus 🐟
Zero to Code

Hi, I’m Christopher (Agnus) Lam. I write about startups, entrepreneurship and marketing.