Tuesday, January 22, 2019


Closures in JavaScript?

I have been looking and playing with web components. I found it a bit too easy to install and use web components in a web page. So I decided to have a good look in how things worked. Geez, I came across a lot of things that I wasnt familiar with. I thought I was a competent Javascript coder. No!

What really puzzled me was  these anonymous functions and these weird self contained function calls of this following format

(function () {
 var Avariable = 'Weird self contained function call';
}) ();


This pattern is a closure. A closure is a combination of  function and the set of available variables in which the closure was defined.

Kyle Simpson's Scope and Closures book ("You don't know JavaScript" book series) said this succinctly; Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Still it is not that clear to me. I dug up my old Sitepoint book "The art and science of JavaScript", and I learnt that a closure is created when a function is defined within another function. If the inner function is accessed from outside of its containing function, it still has access to the scope in which it was originally defined even though the variables in that scope are not accessible to any other functions or variables.

A bit better... As I am a visual learner, I created a simple function with an inner function and used the Console which is a part of Chrome browser to see how it works.


// an outer function createfunction() and an inner function returnAValue that still has access to
// the aValue even when createfunction() goes out of scope.
function createfunction(){
var aValue = 3;

returnAValue = function () {
return aValue;

console.log(aValue); // Undefined
console.log(returnAValue()); // Returns a value of 3.

It makes sense now. Now onto partial function applications.

Partial Function application

Closures are useful for functions that prefill some of their own parameters.


Self executing function pattern 

(immediate invoked function expression)

That was another pattern that got me stumped. I had to play around and now I find them very powerful and very clean. I see them all over the place in well written JavaScript code!

1 comment: