Search code examples
javascriptclassecmascript-6closures

Closures VS Classes in modern Javascript


For closures which main goal it's to create another functions, I was wondering if in modern javascript, it's better to just use classes in modern javascript.

// Closure way private counter
const countPlusOne = () => {
    let count = 0;
    return () =>{
        count++;
        console.log(count);
    }
}
let demoAdd = countPlusOne();
demoAdd(); // 1
demoAdd(); // 2
demoAdd(); // 3

To be honest, I never liked the use of closures in that way (but I think they're great for things like middlewares) as are hard to read.

So, should I refactor closures like the one up, to classes? Their behavior seem more analogous to typical Objects from other languages.

// Class way private counter
class countPlusClass{
    count = 0;
    add(){
        this.count++;
        console.log(this.count)
    }
}
const demo = new countPlusClass();
demo.add(); // 1
demo.add(); // 2
demo.add(); // 3


Solution

  • No, classes aren't always better. They're just different. I'd say the main differences are

    • the interface of the thing returned by the constructor/factory function. A class instance has properties and methods, and usually multiple of them, whereas a closure is simply a function that you can call - with a single functionality. The syntax to invoke them is different, the extra method name is sometimes superfluous and sometimes beneficial.
    • In OOP, objects are expected to have an identity and a state. In FP, functions are expected to be pure. Sure, you don't need to follow a specific paradigm, and stateless objects are fine as are impure functions (though maybe call them "procedures" then), but keep these conventions in mind when arguing about readability and maintainability.

    So choose wisely. Do you (possibly in the future) need multiple methods? Do you encapsulate state? Then use a class to create objects. Do you only need a function to call? Then create a closure.