How To Define A Class In Javascript

6 min read

Defining a class in JavaScript is one of the most important skills you can develop as you move from writing simple scripts to building structured, maintainable applications. Plus, since the introduction of ES6 (ECMAScript 2015), the class keyword has given developers a clean, readable syntax for creating objects with shared behavior. This article walks you through how to define a class in JavaScript step by step, covering class declarations, class expressions, constructors, methods, inheritance, static members, and the mistakes that trip up beginners Not complicated — just consistent..

What Is a Class in JavaScript?

A class is a blueprint for creating objects. It bundles together data (properties) and behavior (methods) into a single, reusable template. When you create an object from a class, that object is called an instance, and the process is called instantiation.

It sounds simple, but the gap is usually here.

It is worth knowing that JavaScript classes are not a completely new object model. Because of that, under the hood, they are syntactic sugar over JavaScript's existing prototype-based inheritance. The class syntax makes the code easier to read and reason about, but the prototype chain still does the heavy lifting behind the scenes Worth knowing..

How to Define a Class in JavaScript: The Two Main Approaches

There are two primary ways to define a class: using a class declaration and using a class expression.

1. Class Declaration

A class declaration is the most common and readable form. It starts with the class keyword, followed by the class name (written in PascalCase by convention), and a pair of curly braces And that's really what it comes down to..

class Student {
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }

  introduce() {
    return `Hi, I'm ${this.name} and I'm in grade ${this.grade}.

const mia = new Student("Mia", 10);
console.log(mia.introduce());
// Hi, I'm Mia and I'm in grade 10.


Key points to remember:

- The **`constructor` method** runs automatically every time you create a new instance with the `new` keyword.
- Methods inside a class body are written **without commas** between them.
- Class declarations are **not hoisted** in the same way function declarations are. You must define the class before you use it.

### 2. Class Expression

A class expression assigns a class to a variable. It can be anonymous or named.

```javascript
const Teacher = class {
  constructor(subject) {
    this.subject = subject;
  }

  teach() {
    return `Today we are learning ${this.subject}.`;
  }
};

const mrLee = new Teacher("Biology");
console.log(mrLee.teach());
// Today we are learning Biology.


Class expressions are useful when you need to pass a class as an argument, return it from a function, or create it conditionally. A named class expression is also handy for debugging, because the name appears in stack traces.

## Understanding the Constructor Method

The **constructor** is a special method that initializes a new instance. It is where you assign initial values to properties using `this`.

```javascript
class Book {
  constructor(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.isRead = false;
  }
}

const novel = new Book("The Quiet Shore", "A. Here's the thing — rahman", 320);
console. log(novel.

A few rules apply:

- Each class can have **only one constructor**.
- If you do not define a constructor, JavaScript provides an **empty default constructor**.
- You must use the **`new` keyword** to create an instance. Calling a class without `new` throws a `TypeError`.

## Adding Methods to a Class

### Instance Methods

Instance methods are functions available on every object created from the class. They can access the instance's properties through `this`.

```javascript
class Counter {
  constructor() {
    this.count = 0;
  }

  increment() {
    this.count += 1;
    return this.count;
  }

  reset() {
    this.count = 0;
  }
}

Getters and Setters

Getters and setters let you control how properties are read and written. They look like properties from the outside but behave like functions internally That's the whole idea..

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  }

  set fahrenheit(value) {
    this.celsius = (value - 32) * 5 / 9;
  }
}

const temp = new Temperature(25);
console.log(temp.fahrenheit); // 77
temp.fahrenheit = 212;
console.log(temp.

### Static Methods and Properties

Static members belong to the **class itself**, not to individual instances. They are ideal for utility functions related to the class.

```javascript
class MathHelper {
  static square(n) {
    return n * n;
  }
}

console.log(MathHelper.square(6)); // 36

You cannot call a static method on an instance — only on the class name That's the part that actually makes a difference. Less friction, more output..

Private Fields

Modern JavaScript supports private fields, declared with a # prefix. They cannot be accessed from outside the class body, which helps protect internal state Not complicated — just consistent. No workaround needed..

class BankAccount {
  #balance = 0;

  deposit(amount) {
    this.#balance += amount;
    return this.#balance;
  }
}

const account = new BankAccount();
console.log(account.Consider this: deposit(100)); // 100
// console. log(account.

## Class Inheritance with `extends` and `super`

Inheritance allows one class to build on another. Use the **`extends`** keyword to create a subclass, and **`super`** to call the parent constructor or parent methods.

```javascript
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    return `${this.name} barks.`;
  }
}

const rex = new Dog("Rex", "Labrador");
console.log(rex.speak()); // Rex barks.


Important inheritance rules:

- You must call **`super()` before using `this`** in a subclass constructor.
- A subclass **inherits all methods** from its parent unless it overrides them.
- You can call a parent method explicitly with `super.methodName()`.

## Classes vs. Traditional Function Constructors

Before ES6, developers

Before ES6, developers relied on **constructor functions** and the **prototype chain** to achieve similar behavior. While classes are syntactic sugar over this prototype-based system, they offer a cleaner, more familiar syntax for developers coming from class-based languages.

```javascript
// Traditional constructor function
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  return `Hi, I'm ${this.name}`;
};

const alice = new Person("Alice", 30);
console.log(alice.greet()); // Hi, I'm Alice

Key differences between the two approaches:

Aspect Constructor Functions ES6 Classes
Syntax Function + prototype assignments Single class block
Inheritance Manual prototype chaining (Child.So naturally, create(Parent. Also, call(this, ... prototype.prototype = Object.) or Parent.call(this) super(...That said, method. ) or super.prototype))
Super calls Parent.method()
Hoisting Function declarations hoisted fully Class declarations hoisted but in TDZ (temporal dead zone)
Strict mode Optional Always enforced in class body
Non-enumerable methods Requires `Object.

When to Use Which?

Use classes when:

  • Building new applications with modern JavaScript
  • Team members are more comfortable with class-based OOP
  • You need private fields (#field) or static blocks
  • Code readability and maintainability are priorities

Stick with constructor functions when:

  • Working with legacy codebases
  • Need dynamic prototype manipulation at runtime
  • Building extremely lightweight objects where class overhead matters (rare)

Mixins and Composition Over Inheritance

JavaScript's single inheritance model (extends only accepts one parent) sometimes leads developers toward mixins or composition for sharing behavior across unrelated classes.

// Mixin pattern
const Loggable = {
  log(message) {
    console.log(`[${this.constructor.name}] ${message}`);
  }
};

class User {
  constructor(name) {
    this.name = name;
  }
}

Object.assign(User.prototype, Loggable);

const user = new User("Ada");
user.log("Initialized"); // [User] Initialized

Alternatively, composition favors small, focused objects combined at runtime:

const withLogging = (obj) => ({
  ...obj,
  log(message) {
    console.log(`[${obj.constructor?.name || "Object"}] ${message}`);
  }
});

const user = withLogging({ name: "Ada" });
user.log("Created via composition");

This approach avoids rigid hierarchies and makes behavior easier to test and reuse.


Conclusion

JavaScript classes provide a powerful, expressive way to structure object-oriented code while staying true to the language's prototype-based roots. From basic constructors and methods to advanced features like private fields, static members, and inheritance with super, the class syntax covers the full spectrum of OOP needs.

Understanding both the class syntax and the prototype mechanics underneath gives you the flexibility to choose the right tool for the job — whether that's a clean class hierarchy, a functional composition pattern, or a hybrid approach. As JavaScript continues to evolve, classes remain a foundational building block for scalable, maintainable applications.

Just Published

Newly Added

Readers Also Loved

One More Before You Go

Thank you for reading about How To Define A Class In Javascript. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home