Do you need classes in JS/TS?

András Tóth - Feb 7 '22 - - Dev Community

If you are starting out as a developer, you might run into these conflicting schools of thought: should I write "functional style" with its "pure functions" or go with "object oriented classes"?

The answer would be really long and this is going to be just a quick tip.

Beforehand it is important to know that Javascript (and consequentially TypeScript) is neither functional nor an object oriented language. It has elements of both and it breaks important contracts of either. See the last paragraph: "Only for the curious!".

If you are going to have several similar objects that persist over time (i.e. you keep them around for a long time and you regularly) and have some form of state that you access a class is a really good choice. However if you just need to transform an object to another object a function is your best bet.

The symptoms of not needing a class

The feature a class is truly giving us is accessing this in any of the defined functions. When some or more of your class methods do not access this and only the parameters passed and they also return the result, then you will need a function. Even better if you can make the function pure (in other words none of the parameters passed in are mutated)...

The algorithm to refactor this

  1. Find a class method that do not access this. Extract it into a method and update the depending methods.
  2. Check the class again, if the changed methods no longer access this: move them out as well.
  3. If every method access this you have the real class that is actually managing its own state.

Only for the curious

The classic example of breaking the functional paradigm is that on an array .sort() method mutates the array, while .map() returns you a new array instance. This is inconsistent and creates regular problems.

On the other hand objects created from traditional classes "own" their own functions, while in Javascript you can pass the function of an object and lose its this. You can also bind a function to a totally different object. There is a lot of frustration voiced when this phenomenon dawns on a developer coming from real object oriented background.

Questions, mistakes or do you wish examples? Blogging and learning is a collaborative effort, I need your help to help you. 🤝 Let me know in the comments! Cheers!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .