DEV Community

Jeremy Moore
Jeremy Moore

Posted on

Seeking some closure

Introduction

As part of my effort to better understand how functions work in Javascript, I had reviewed the concept of closure and how powerful it can be when it comes to organizing code. I won't go over closure here, but you can read more from Mozilla here. The specific issue I dealt with involved accessing the closure variables in an inner function.

Can't see bloody A,B,C or D

A situation I had never encountered before involving the Scope debugging panel in Chrome. I was attempting to determine the value assigned to a variable by a function call while inside a nested function. A simplified version of the scenario is below:

function testing() {

    var a = "modern";
    var b = "major";
    var c = "general";

    function innerFunction() {
        console.log(`Not using parent function var`);
    }

    innerFunction();

};

If you were to run the function testing(), you would see that there is no sign of the variables a,b or c if a breakpoint is placed inside the innerFunction().

Image of Chrome debugger sidebar

I can't see you

What I discovered was that the values of references in the outer function are not visible in the inner function unless they are actually used. Making a one line change to the above example results in this:

function testingClosure() {

    var a = "modern";
    var b = "major";
    var c = "general";

    function innerFunction() {
        console.log(`Using parent function var, value: ${a}`)
    }

    innerFunction();

};

The outer testingClosure() function variables are now available inside the innerFunction() for debugging.

Image of Chrome debugger sidebar with closure variables

I had originally wanted to examine the value of a inside the inner function without writing any code, but due to the way browser debugging works, there was no way around it.

Codepen

You can experiment with closures here:

Try placing a debugger statement in the inner function and see the scope difference.

Top comments (0)