What is Closure and Lexical Scoping?

What is Closure and Lexical Scoping?

Have you recently started learning JavaScript? What motivated you to learn the language? For me, I used to be a web designer and I always was and still am fascinated by the transition of static prototypes into the dynamic web and mobile applications. That's how I started coding. If you have a passion for coding, a willingness to learn and the determination, you can do it, too! Let's roll!

Lexical Scoping

function multiply(a, b){
    return a * b
}

function multiplyByInnerVar(c){
    const a = 1;
    return c * a;
}

let a = 0;

multiply(a, 100);  // return 0
multiply(a, b); // throw an error as b is not defined.

a = 5;

multiply(a, 5) // return 25, not 0
multiplyByInnerVar(10);  // return 10, not 50

As you have read the codes above, lexical scoping defines the environmental state of the function and the returned values are defined by the values of the variables a within their lexical scoping as each function referenced to a different value, but with the same variable name a.

When you define a variable globally, you create a new environmental state and when you declare a function, you also can create a local environmental state inside the function. The location of variables will create the lexical scoping and if a function cannot reference any local variable, it will try to find another variable to access from the outer scopes, eventually looking to the global one. This is called Hoisting.

In the past, var was the only keyword to declare variables in JavaScript. and it made me really puzzled to understand all of these concepts when I first started learning JS. Thankfully, since we have the arrow function, the keywords const and let from ES6, the codes become more readable and traceable even without debugging.

Closure

// First example
function greetings(greet){
    const secretAgent = sayMyName();
    return `${greet}, ${secretAgent} !!!!`;

    function sayMyName(){
        const emilie = 'Emilie';   
        // We are not able to access to this variable directly by any means.
        return emilie;
    }
}

greetings('Hello');  // return 'Hello, Emilie !!!!'
greetings('Good Morning'); // return 'Good Morning, Emilie !!!!'
// Second example
function multiply(a){
    let b = 10;
    return function() {
        return a * b
    }
}

const reference = multiply(5); 
// there is no returned value at this point.
// we just create a new variable `reference` to access to the inner anonymous function.

reference(); // returns 50

const anotherReference = multiply(10);
anotherReference (); // returns 100

Closure is very useful when you actually start building something with JavaScript.

In a certain case, you want to protect a certain piece of data assigned to a variable. So as to do that, you implement closure for the encapsulation of local variables. The variables are no longer able to be accessed directly from outer scopes. The only way we can see the value of the variable emilie is the invocation of the outer function greetings.

This encapsulation not only prevents the global variable pollution but also, protects a local variable being accessed from outer scopes. and another benefit of closure is that you can minimise the memory leak. As the emilie variable is not assigned globally, the memory allocation only occurs when the greetings function is invoked.

And Closure lets us create its own lexical scoping which can be referenced later even from outer scope like the 2nd example above. This can be used to more effectively allocate the memory for the retention repetitively. But, you may also take into consideration memory leak as it could hold the memory for the retention from the call stack.

Now you know the lexical scoping and Closure, you can learn JavaScript further such as, call stack, memory leak and Immediately Invoked Function Expression(IIFE) and so on. If these topics didn't put you off learning more JavaScript, I believe no matter what background you have and which gender you are, you are truly tech-savvy. Let's swim in the abyss sea of JavaScript together. I will come back again soon. Thank you for reading!