I was reading this example on w3schools about Javascript closure applied to the "counter dilemma":
https://www.w3schools.com/js/js_function_closures.asp
In practical use, this example seems almost nonsense. Why should I wrap the variable "counter" into a closure, protecting from accidentally modifications in global scope, when I can't protect the variable "add" containing the function itself?
To be more specific... I have this code:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
W3schools says at start: "The problem is, that any script [in global scope] on the page can change the counter, without calling add()."... the closure above is proposed as a solution. Ok. But what about protecting "add" from subscribing? This make the variable still "vulnerable".
So, what is the advantage of closure implementation?