Home About SAIT News & Events Closures in JavaScript - a powerful tool in your JS toolbox (part 1)

Closures in JavaScript - a powerful tool in your JS toolbox (part 1)

June 12, 2015


Friends, colleagues, lend me your eyes and I'll explain one of the concepts frequently viewed as some sort of JS voodoo — closures.

Originally coined by Peter J. Landin in 1964, Wikipedia defines the term to refer to an "a lambda expression whose open bindings (free variables) have been closed by (or bound in) the lexical environment, resulting in a closed expression, or closure". Great. So... that means what, exactly?

For JavaScript, in which everything is an object, this means that a closure is an object of function type in which all the function's variables are resolved with the values that were in scope when the function was defined. It should be noted that understanding scope, then, is absolutely critical to understanding closures.

Scoping Basics

Consider the following example:

pitch = "alto";            //Global scopefunction meghanTrainer(iterations) {

var pitch = "bass",   //meghanTrainer scope

innerFnClosure = function(){

var pitch = "treble";      //innerFnClosure scope

console.log(", no "+ pitch + ".\n");

}

console.log("Because you know ");

for (var i  = 0; i<= iterations; i++) {

console.log("I'm all about that " + pitch + ", \n'Bout that " + pitch);

innerFnClosure();

}

}

meghanTrainer(4);

As a side note, this is also how most modern languages (including C, Lisp and their derivatives) have been developed. This allows programmers to operate within the confines of their program and make assumptions on the possible values of their variables, rather than trying to account for all possible values at runtime.

So, we now understand what a closure is, and what scope means for closures. Stay tuned for part 2, which will outline classic use cases.

By Stephanie Krause

Share:
Enter Your Search Term Here
Start typing to search SAIT.ca
 
REFINE RESULTS
Refine Results
 
 


Search results