yup, that's exactly what the example code will do. In Javascript, when you execute a function, it creates a closure, which contains all the variables created during the execution. You can think of it like a dynamically allocated stack frame. That closure is reference counted, so as soon as there are no more references to it, it goes away. Anything created within the closure has implicit access to it, and maintains a reference. The practical upshot is that when you define a function within the execution of another function (within its closure), and then return that function outside of the scope, it still maintains access to that scope, but nothing else does. That effectively gives it private, persistent variables that behave largely like static variables in C++. const func = (()=>{ //< This defines a function
// inside the closure
let psuedoStatic = 0;
return (a,b) => { //< This returns a function out of the closure
psuedoStatic = (psuedoStatic * a / b)
return psuedoStatic;
};
})(); //< this calls the first function, returning the second to be stored in the func variable This pattern is pretty common in Javascript, particularly before the introduction of classes in ES6. This is how the Revealing Module Pattern works, though in that case you're often returning an object and using the closure for what would be private variables in C++ (Javascript lacked a concept of private variables until very recently). The outer function, which is just responsible for setting up the closure and returning the function with access to it, is called an IIFE (if-y), or Immediately Invoking Function Expression. The invocation happens on the last line, with those trailing () there. One place that this technique varies from static variables in C++ is that if you kept the outer function around, you could manufacture many of the inner function, all with their own set of private variables. Basically a factory function. Here's an example: const counterMaker = () => {
let n = 0;
return () => ++n;
};
Calling this function will return a function which returns a series of monotonically increasing integer values. Each time you call it, you get a new, unrelated counter.