What type of function is this?

What type of function is this? Is it like annonymous funtion that holds other functions including return statement that returns object like key’s with assigned functions that do certain operations? I found this code somewhere but it’s my first time seeing something like this. Can someone explain this type of funciton/code? Thanks.

var counter = (function() {
    var myCounter = 0;

    function changeBy(val) {
        myCounter += val;
    }

    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function() {
            changeBy(-1);
        },
        value: function() {
            return myCounter;
        }
    };
})();

console.log(counter.value());
counter.increment();
counter.increment();
console.log(counter.value());
counter.decrement();
console.log(counter.value());
counter.changeBy(2);
console.log(counter.value());

this function uses closure to create a counter

you have this object that has the methods to increase, decrease and see the value, which is returned by teh function so can be accessed as counter.value() etc

the value lives inside this function in the variable myCounter

so it can’t be accessed by outside, and the only way to change the value is to use the three methods

Also a function like this

is a IIFE, Immediately Evoked Function Expression

1 Like

The basic of it is a factory function, which is a function that returns an object, and the IIFE turns it into a module pattern.

Here is a nice rundown of the two patterns.

More reading

1 Like