Javascript Closure — from a Junior dev point of view

Brett Cole
2 min readFeb 19, 2018

--

What exactly is Javascript closure? What is it used for? Let’s break this fundamental principle down and use it in our future code. In his blog series about mastering the Javascript Interview Eric Elliot made this comment about closure questions.

If you can’t answer this question, you’re a junior developer. I don’t care how long you’ve been coding.

Harsh? Absolutely! Motivating? It should be. So let’s get to it. MDN describes a Javascript closure like this -

A closure is the combination of a function and the lexical environment within which that function was declared.

Is it just me or does it always seem like your more confused after reading MDN’s description? I thought Javascript is Sexy’s description really helped describe it.

A closure is an inner function that has access to the outer (enclosing) function’s variables — scope chain.

Time for an example to better understand exactly what is going on.

// Let's keep it simplelet a = 'global variable';function closureExample() {
let b = 'outer function variable';

function closureFunction() {
let c = 'inner function variable';
return a + ' ' + b + ' ' + c;
}
return closureFunction();
}
closureExample(); // 'global variable outer function variable inner function variable'

A closure has 3 scope chains -
1. it’s own scope (variables defined between it’s own curly brackets) — or — `let c` in the function above
2. variable declared inside the outer function — or — `let b` in the function above
3. global variables — or — `let a` global scope above

Closures are also very popular in creating private functions and used with the Modular JS design pattern. Let’s take a look at a private function which is inside an outer function.

function example() {
let amount = 1000;
function privateFunction(ind) {
return amount += ind;
}
return {
a: privateFunction(100),
b: privateFunction(2000)
}
}
example(); // { a: 1100, b: 3100 }

With this example `privateFunction(ind)` is considered a private function because it is not accessible to the outside world. Javascript Closures are a very important fundamental to grasp that will only come with experience and practice. But are a must if you want to expand your knowledge and be considered a legitimate developer.

There are plenty of other examples where closures are used. For example with Classes and inheritance. But that’s for another day. On to the next topic. Bye.

--

--

Brett Cole
Brett Cole

Written by Brett Cole

Full Stack Developer. Husband. Father.

Responses (1)