function outerFunction() {
    const outerVariable = "outer scope";

    function innerFunction () {
        console.log(outerVariable);
    }

    innerFunction ();
}


outerFunction()

// outer scope

Lexical Scoping

 

The innerFunction being able to access the variables in the outer function is called "lexical scoping".

It is about how functions and variables interact based on their position in the code.

Lexical means : relating to words or vocabulary of a language. Also semantic meaning.

- Lexical vs dynamic

Dynamic scope- the function gets scope by how it is called. The scope can be different.

Lexical scope - is about where the function sits within the code. 

 

 

 

Closures

A closure in JavaScript is a combination of a function and the lexical environment.

 Normally a function within a function. Outer function returns another inner function

(a function is part function/ part object).

 

Note: A closure is bit like a Class instance 

 

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

 

function createCounter() {
   let count = 0


   return function() {
       count++

       console.log(count)
   }
}


const closure1 = createCounter()
const closure2 = createCounter()

closure1()
closure1()
// 1
// 2

closure2()
// 1

 

Benefits of Closures

 • Encapsulation of a state / scope for a given function.

Data is private but can be modified by a function.

 

• Persistent data and state. Each time the outer function is called it creates a new closure with its own variables.

 

• Code reusability - The closure returned reuses the code.

  

Disadvantages of Closures

• memory leaks if not properly managed. Closures retain references to the variables they access. 

 

How to release the variable reference / closure from memory?

 You set the reference to the closure to null

closure1 = null

closure2 = null

 

The different  between a regular function and a closure

A regular function does not retain access to their reference variables after execution completes.

A closure retains access to their reference variables even after the execution completes.