What is Closures in JavaScript?

What is Closures in JavaScript?

What is Closures?

Closure is a function inside a function that has access to variables in outer functions.

  • function first is ran and executed when assigning the return value to newFunc. first will not be executed again.

  • child scope has access to its parent scope(inner function has access to outer functions' scope)

  • function inside function

const first = () => {
    // local variable - created everytime this function runs
    const greet = 'Hi';
    const second = () => {
        alert(greet);
    }
    return second;
}

const newFunc = first();
// calling first() means:
// const newFunc = () => {
 // alert(greet);
// }
newFunc()

When do we use it?

Data encapsulation

const createBankAccount = () => {
      let currentBalance = 0;

      const changeBy = (amount) => {
        currentBalance += amount;
    }
    return {
        deposit(amount){
           changeBy(amount)
        },
        withdraw(amount){
            changeBy(-amount)
        },
        balance(){
            return currentBalance;
        }
    }
}

const bankAccount1 = createBankAccount();
const bankAccount2 = createBankAccount();

console.log(bankAccount1.balance()); // 0
bankAccount1.deposit(100);
bankAccount1.deposit(100);
console.log(bankAccount1.balance()); // 200

bankAccount1.withdraw(50);
console.log(bankAccount1.balance()); //150

console.log(bankAccount2.balance()); //0
  • Two bank accounts are independent from one another. Each closure refers to a different version of its currentBalance

Function factory

const createDirectory = (name) => {
    return {
        name,
        message: () => {
            console.log(`${name} has been added to your directory.`)
        }
    }
}

const mike = createDirectory('Mike');
mike.message(); // Mike has been added to your directory.

const lisa = createDirectory('Lisa');
lisa.message(); // Lisa has been added to your directory.
  • A function creates an object and return it using the input

Performance considerations

Closure affect performance(processing speed & memory consumption) as each function instance manages its own scope and closure

// mike is function instance managing its scope and closure
const mike = createDirectory('Mike');
// lisa is function instance managing its scope and closure
const lisa = createDirectory('Lisa');