Closure in Javascript

Cindy Zheng
2 min readAug 31, 2020

--

“A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.”

Key Points:

Closure is a function returns another function.

Inner function will have access to the outer function.

Variables from outer function’s scope persist.

Example:

We have an outer function called outer(). It creates a local variable called counter and a function called inner(). The inner function also has a local variable called innerCounter and the inner function can access the variable (counter) from outer function:

myFunc is a reference to the inner function that is created when outer function is run. This prevents the outer scope to be destroyed. In this case, myFunc will reference the same outer scope. So when the variable counter changes it will persist the change to the next call. The results will be:

console.log(counter, innerCounter)

first time call myFunc: counter:1, innerCounter: 1

second time call myFunc: counter:2, innerCounter: 1

third time call myFunc: counter:3, innerCounter: 1

Sources:

--

--

No responses yet