Member-only story
Do you want to take your JavaScript performance to new heights? Then look no further than closures and memoization. With these advanced techniques, you can significantly speed up your code and avoid unnecessary calculations.
Let’s begin by discussing closures. At its core, a closure is a function that remembers its outer environment, even after the outer function has finished executing. Essentially, closures capture free variables — those not defined within the current function but used inside it.
Here’s an example demonstrating how closures work:
function outerFunction(x) {
const y = x * 2;
return function innerFunction(z) {
return y + z;
};
}
const addTenToDouble = outerFunction(5);
console.log(addTenToDouble(10)); // Output: 20
In this snippet, outerFunction
takes an argument x
and returns a nested function innerFunction
that uses the captured y
. When invoking outerFunction(5)
, we store the resulting innerFunction
in a constant named addTenToDouble
. Notice how addTenToDouble
retains knowledge of y
despite outerFunction
having completed its execution.