When to Use Classes in JavaScript

You might have always found youself just using functional programming.

You've seen examples of OOP like classes representing animals or cars, but you've never seen any examples that apply to web development. This makes it hard for you to understand their benefits.

So what are some common scenario to use classes in JavaScript? When is a good time to use them?

Classes encompass state and behaviour. This is different (conceptually) to functions, in which the state is passed to the function. Things where state and behaviour are intricately intertwined are good uses for classes.

UI elements comes to mind. If a button is disabled (i.e. disabled state = true), it shouldn't be clickable (i.e. click behaviour is different).

However, don't get too bogged down in culture wars over OOP vs other approaches. OOP, functional, procedural, whatever. They're all ways of organising code, of thinking about problems and solutions. None is better than the other. You can use classes to do anything, and the same is true of functions.

I look at it as "well, if I can do this thing in 4 lines of functional code, but it takes 20 lines of code to do it the OOP way, I'll choose the functional way". Similarly, if I'm looking at a problem and it takes some weird and wacky functional approach where a class would be easier to understand, I'll choose a class.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda