albertofortes

UI engineer | front-end React developer

JavaScript, Interview Question series, JavaScript fundamental topics,

JavaScript Closures in 2 minutes

2021-04-24

JavaScript Closures in 2 minutes

React interview cheatsheet series

A variable in javascript can be global or local. A global variable can be done private using a closure.

Closure can seems a difficult concept at the beginning, but if you did some code in JavaScript or you are a React developer, you already used closures thousand of times.

An example of a closure in a Immediately-invoked Function Expression (IIFE):

1const counter = (function() { 2 const resultBox = document.getElementById('result'); 3 let _counter = 0; 4 resultBox.innerHTML = _counter; 5 6 function addOne() { 7 _counter++ 8 resultBox.innerHTML = _counter; 9 return _counter; 10 } 11 12 function subtractOne() { 13 _counter-- 14 resultBox.innerHTML = _counter; 15 return _counter; 16 } 17 18 return { 19 addOne, 20 subtractOne 21 } 22 23})(); 24 25console.log( counter.addOne() ); // 1 26console.log( counter.addOne() ); // 2 27console.log( counter.subtractOne() ); // 1

See code above at codepen.

At the code above we have a IIFE with some nested function, all these nested functions have access to the private function _counter. The const counter is assigned to the return value of a self-invoking function. The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression. This is called a JavaScript closure. It makes it possible for a function to have private variables. The _counter is protected by the scope of the anonymous function, and can only be changed using the add function. So, A closure is a function having access to the parent scope, even after the parent function has closed.