A closure having nested closures with the depth of more than 2 levels is less readable, slower in performance and hold excessively large private memory causing memory leaks.
Impact
- A heavily nested closure is complex to read and maintain.
- Creating closures inside other closure leads to duplication in memory, potentially slowing down the application.
Characteristics
A function that returns an inner function where the inner function will have access to the outer scope even after the outer function is executed.
function foo() { var height = 10; function bar() { console.log(height); function counter() { var area = 62; function privateCounter() { console.log(area); function myFunc() { var square = 21; function funcA() { console.log(square); function getMeasure() { var measure = 27; function setLogs() { console.log(measure); } return setLogs; } var test = getMeasure(); test(); } return funcA; } var secret = myFunc(); secret(); } return privateCounter; } var invoke = counter(); invoke(); } return bar; } var something = foo(); something();
Solution: Move the logic of inner closures into separate closures if they are independent of each other or if the inner closure does not require the lexical scope of the outer function.
function foo() { var height = 10; function bar() { console.log(height); } return bar; } var something = foo(); something(); function counter() { var area = 62; function privateCounter() { console.log(area); } return privateCounter; } var invoke = counter(); invoke(); function myFunc() { var square = 21; function funcA() { console.log(square); } return funcA; } var secret = myFunc(); secret(); function getMeasure() { var measure = 27; function setLogs() { console.log(measure); } return setLogs; } var test = getMeasure(); test();
Guidelines
- When the lexical scope of inner function is independent of the outer functions, closures are not required as closures consume unnecessary system resources.
- The closure impacts the lifetime of its private state. The private state will be garbage-collected only after the outermost closure function is collected.
- Unless you need data privacy, it is more practical to use the module pattern to create new objects with shared methods.