Mastering Closures: Building a Calculator in Javascript

Closures are one of the most powerful and often misunderstood features of JavaScript. They allow you to encapsulate state within a function and create private variables that are accessible only within that function’s scope. In this interview article, we’ll explore how to leverage closures to create a simple yet powerful calculator function in JavaScript.

Understanding Closures

Before diving into building our calculator function, let’s briefly review what closures are and how they work in JavaScript.

A closure is formed when a function is defined within another function (the outer function) and has access to the outer function’s variables. This inner function preserves the scope chain of the outer function even after the outer function has finished executing. As a result, the inner function retains access to the variables and parameters of the outer function.

Building the Calculator Function

Our goal is to create a calculator function with an initial value of 10 as the base. This function should provide two methods: add() and sub().

Here’s how we can implement it using closures:

function createCalculator() {
  let baseValue = 10;

  function add(num) {
    baseValue += num;
    console.log(baseValue)
  }

  function sub(num) {
    baseValue -= num;
    console.log(baseValue)
  }

  return {
    add,
    sub,
  };
}

Calculator Function Explanation

  • We start by defining a function called createCalculator(), which serves as the outer function.
  • Within createCalculator(), we declare a variable baseValue and initialize it to 10.
  • Inside createCalculator(), we define two inner functions: add() and sub(). These functions have access to the baseValue variable due to closures.
  • The add() function increases the baseValue by the specified amount.
  • The sub() function decreases the baseValue by the specified amount.
  • Finally, we return an object containing references to the add(), sub() functions, effectively creating a closure over the baseValue variable.

Using the Calculator

Now that we’ve defined our calculator function, let’s see how we can use it to perform addition and subtraction operations:

const calculator = createCalculator();
calculator.add(5);  // 15
calculator.sub(4);  // 11

Calculator Class Component:

In some cases, the interviewer might expect you to solve this with a class component. Below is the code to create a Calculator class component.

class Calculator {
  constructor() {
    this.baseValue = 10;
  }

  add(num) {
    this.baseValue += num;
    console.log(this.baseValue);
  }

  sub(num) {
    this.baseValue -= num;
    console.log(this.baseValue);
  }
}

// Usage
const calculator = new Calculator();
calculator.add(5); // 15
calculator.sub(3); // 12

we’ve explored how to leverage closures to create a calculator function in JavaScript. By encapsulating the state within the function and providing methods to manipulate that state, we’ve created a reusable and modular component.