In Defense of JavaScript Constructor Functions (Classes)

Posted on

This post has stuff about religion. My perspective has changed

So there’s lots of debate about the merits of pure JavaScript objects (using Prototypal Inheritance) vs constructor functions (classes). I was on the former bandwagon until recently when I realized there are a couple of really good reasons to use classes.

Assume the following: I have a situation where I use/reuse a single object in many different methods throughout my app. It gets modified and munged and poked and prodded until finally it dies a horrible death and disappears into the ether.

Simplified validation and object setup

Every method tests the object for the properties that it cares about before it does any processing. It can be as few as three validations and as many as 10. Well lets say I have even 20 methods with an average of six validations each. That’s 120 various checks. But with constructor functions I could reduce that to one—when the object is initialized. At that point data is validated and errors are thrown. By simply checking if the object is instanceof Type in each method I can drastically reduce the amount of pre-processing I have to do before an object is ready for prime time.

Smaller, more readable codebase

Less method-level validation equates to smaller codebase. Seriously, if I don’t have to write x !== undefined five or six times in every method that’s a significant file-size reduction. It may not perform better (I haven’t tested it yet) but it’s a helluva lot easier to read and a lot less error prone. Assuming I put each validation on a single line I’ve just saved 120 lines of code. This is pretty compelling IMHO .

Adds well-defined rules to an application

In this scenario a developer cannot simply create a similar object to be used in place of the properly vetted/validated one. Instead the developer must create an instance of the well-formed object. This is great for devs who are new to a project or who are still honing their chops. It means less hackery and cleaner code.


In no way do I intend this as a whole-sale endorsement for constructor functions over regular objects. In fact, if inheritance is involved I almost always use Prototypal Inheritance with regular old objects. But in this specific scenario they’re a great fit. In other words, always use the best tool for the job.