Tip 37: Build Readable Classes

In this tip, you’ll learn how to create extendable classes in JavaScript.

Classes in JavaScript

One of the longest-running criticisms of JavaScript was that it lacked a class syntax. Well, it’s here! But it didn’t arrive without controversy. Proponents of classes argue it’s a common development paradigm that’s very familiar to developers in other languages. Skeptics think it obscures the underlying nature of the language and encourages bad habits.

Like many controversies, the rhetoric is excessive. Classes are now part of JavaScript, and if you use any popular framework such as Angular or React, you’ll introduce them in your code. And that’s great.

As you’ll see in Tip 39, Extend Existing Prototypes with Class, the base language hasn’t changed. JavaScript is still a prototype-based language. Now you have familiar syntax masking slightly complicated concepts. As a result, there are some surprises.

In this tip, you’ll get a quick look at how to write classes in JavaScript. If you’ve written classes in any other language, the interface should seem pretty familiar.

Example: Making a class

To start off, make a class called Coupon. You declare a class with the class keyword. You can then create new instances using the new keyword.

Get hands-on with 1000+ tech skills courses.