Enjoying Closure

Jason Sigmon
JSON’s Coding Adventures
1 min readJan 27, 2017

Closure is something that certainly confused me when I started, but I want to make it easier and hopefully more practical for other people. The most basic version is allowing an inner function access to variables outside of its scope.

let runner = (a)=> {
console.log(a);
let b = 3;
(() => {
let c = 20
console.log(a); // 2
b = 5;
console.log(b); // 5
console.log(a+b); // 7
})()
console.log(b) // 3
console.log(c) // not defined
}
runner(2);

In the above example, we are able to change the value of b in the inner function without affecting the value of b in the outer function. This is a great way to use closure to prevent side effects.

A more practical way to think about it, is to imagine a business that’s expanding to a new country. You have your normal rules and procedures that govern the entire company, but as the New Zealand country manager, you can make small adjustments. You decide instead of 10 vacation days for employees, you will allow employees to take 12 vacation days. As a member of the New Zealand branch of Acme Corp., you could enjoy 12 vacation days. Members of Acme Corp. HQ would still only have 10 vacations days. Just like that example, Closure gives you the power to allow for adjustments or new variables within your enclosed functions.

--

--

Jason Sigmon
JSON’s Coding Adventures

Founder of Arternic, LCS Fan, and tweet @jaysig91. Feel free to reach out and say hello