DEV Community

Cover image for Getting Closure
jordan-mann
jordan-mann

Posted on

Getting Closure

As time consuming as coding can be, understanding efficiencies is a critical component of effective programming. Being able to cut back on your global scope to have more function-lexical scoping is huge. It both cuts down on the need to create everything in the global scope of a program, and also allows one to reuses variable names inside of functions scopes.

Closure allows functions to have access to any variable contained in a parent function’s scope, rather than those variables being locked and exclusive only to that individual function. These function scoped variables are not available to all functions, but only to functions that are nested within outer functions. The reverse is not true. Variables within a nested function will not be accessible to outer functions.

While closure is a feature that comes with how scope works in the JavaScript language, it brings with it an advantage that can be exploited by developers: lexical scoping. Because of how closure works in allowing functions to access values of functions they are nested in, it allows developers to create a bind variables to be executed within a function. This prevents developers from needing to create every variable in the global scope in order to access them, and thus being able to use a variable only once. Because of closure, a set of nested functions can almost act as their own mini- or sub-global scope – and lexical scope – with variables created in these functions that can be accessed as needed by inner functions. And because these variables are locked within the scope of the functions they were made in, they can be re-used as many times a needed in other function scopes.

Consider the following example:

function greeting() {
  let message = 'Hi';
    function sayHi() {
      console.log(message);
    }
  return sayHi;
}
greeting()();
Enter fullscreen mode Exit fullscreen mode

As you can see, the first function, function greeting() {} takes creates a variable called 'Hi'. Then, and inner function function sayHi() {} takes that variable 'Hi', remembers that its value from the previous function, and keeps that value in itself, logging the value to the console.

This can be done as many times in as many nested functions as needed:

function nameMe() {
    let name1 = 'Captain';
    let name2 = 'America';
        function nameFull() {
            let nameFull = (name1 + ' ' + name2);
              function awesomeMessage() {
                console.log(nameFull + ' is really cool')
              }
          return awesomeMessage;
        }
       return nameFull;
}
nameMe()()();
Enter fullscreen mode Exit fullscreen mode

In this example, the outermost function creates the name1 and name2 variables, the second function, creates the nameFull variable, and the inner most function prints the nameFull variable, keeping the values first defined in the outermost function. Calling the innermost function will run through all the functions, getting our desired result: "Captain American is really cool"

One last example of closure will show how creating different variables assigned to the same function can remember the different arguments passed into it:

function makeName(name1) {
    return function(name2) {
        return name1 + ' ' + name2;
    }
}

let peter = makeName('Peter');
let j = makeName('J');

console.log(peter('Griffin'));
console.log(j('Mann'));
Enter fullscreen mode Exit fullscreen mode

In this example, both variables peter and j are assigned to the same function makeName, but are given different variables. The console log calls the outer function makeName which in turns calls the inner function, which in each case has a different argument passed in. The results will be Peter Griffin" and "J Mann" respectively.

Closure is a great aspect of programming, allowing developers to reuse existing code for different purposes, rather than needing to redevelop code for every single action they want to perform. A good understanding of closure will help build efficiency in programming for any developer and increase the enjoyability of coding.


Enter fullscreen mode Exit fullscreen mode

Top comments (0)