JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Class Intro


JavaScript classes were introduced in ES6 (ECMAScript 2015) to provide a clear and structured way to create objects and implement object-oriented programming concepts.

While JavaScript has always been prototype-based, the class syntax offers syntactic sugar over constructor functions and prototypes. Classes help developers write cleaner, more organized code, especially in large applications where object blueprints, inheritance, and encapsulation are required.

Understanding classes is fundamental for building scalable and maintainable JavaScript applications, and they are heavily used in modern frameworks such as React, Vue.js, and Angular.

1. What is a Class?

A class in JavaScript is a blueprint for creating objects. It defines:

  • Properties: Data that each object will hold.

  • Methods: Functions that operate on the object’s data.

Unlike constructor functions, the class syntax is more readable and intuitive, clearly separating instance properties from shared methods.

2. Basic Class Syntax

The simplest class definition uses the class keyword followed by a name and a body:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const person1 = new Person("Alice", "Smith");
console.log(person1.fullName()); // Alice Smith
  • constructor() is a special method automatically called when an object is created using new.

  • Methods defined outside the constructor are shared via the prototype, not copied to each instance.

3. Advantages of Classes Over Constructor Functions

  1. Clear Syntax: Classes are easier to read and understand compared to constructor functions.

  2. Encapsulation: Properties and methods are clearly grouped.

  3. Inheritance Support: Classes provide the extends and super() syntax for easy inheritance.

  4. Prototype Management: Methods are automatically added to the prototype, saving memory.

4. Creating Class Instances

An object created using a class is called an instance. Each instance has its own unique properties, while methods are shared.

const person2 = new Person("John", "Doe");
console.log(person2.fullName()); // John Doe
  • Properties like firstName and lastName are unique to each instance.

  • Methods like fullName exist once on the prototype and are accessible by all instances.

5. Getters and Setters in Classes

Classes can include getters and setters to control access and update properties:

class Student {
  constructor(firstName, lastName, grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this._grade = grade;
  }

  get grade() {
    return this._grade;
  }

  set grade(value) {
    if (value < 0 || value > 100) {
      console.log("Invalid grade");
    } else {
      this._grade = value;
    }
  }

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const student1 = new Student("John", "Doe", 90);
student1.grade = 105; // Invalid grade
console.log(student1.grade); // 90
  • _grade is a private-like property (convention using underscore).

  • Setters allow validation before updating properties.

6. Static Methods

Static methods are class-level methods not accessible by instances.

class Calculator {
  static add(a, b) {
    return a + b;
  }
}

console.log(Calculator.add(5, 10)); // 15
  • Attempting to call add on an instance will fail.

  • Static methods are useful for utility functions related to the class.

7. Class Inheritance

JavaScript classes support inheritance, allowing one class to extend another:

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

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

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

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

const dog1 = new Dog("Rex", "Labrador");
dog1.speak(); // Rex barks
  • extends creates a subclass.

  • super() calls the parent class constructor.

  • Child classes can override parent methods.

8. Private Fields and Methods

Modern JavaScript allows true private fields and methods using the # prefix:

class BankAccount {
  #balance = 0;

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

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
  • Private fields cannot be accessed outside the class.

  • This feature improves encapsulation and security.

9. Notes and Best Practices

  • Use classes for structured and reusable objects.

  • Define instance properties in the constructor.

  • Place methods outside the constructor for memory efficiency.

  • Use getters/setters for property control.

  • Use static methods for utilities not tied to instances.

  • Use private fields for sensitive or internal data.

10. Summary of the Tutorial

  • Classes are blueprints for creating objects in JavaScript.

  • They support constructors, methods, inheritance, static methods, and private fields.

  • Classes improve readability, maintainability, and organization compared to constructor functions.

  • Mastering classes is essential for modern JavaScript development, including OOP patterns and framework usage.

  • Proper use of classes ensures scalable and efficient code in real-world applications.

Understanding classes provides the foundation for advanced topics like inheritance, encapsulation, and object-oriented design, making JavaScript code easier to write, maintain, and scale.


Practice Questions

  1. Basic Class Creation
    Create a class Person with properties firstName and lastName. Add a method fullName() to return the full name. Instantiate an object and log the full name.

  2. Constructor with Multiple Properties
    Create a class Student with firstName, lastName, and grade. Create two instances and log their properties.

  3. Getters and Setters
    Add a getter and setter for grade in the Student class to validate the grade is between 0 and 100. Test with valid and invalid values.

  4. Static Method
    Create a class Calculator with a static method multiply(a, b). Call it directly from the class and verify it cannot be called on an instance.

  5. Instance Method vs Static Method
    Create a class Car with an instance method info() and a static method compare(). Instantiate objects and test both methods.

  6. Inheritance
    Create a class Animal with a method speak(). Extend it with a class Cat that overrides speak() to print a custom message.

  7. Using super()
    In a child class, call the parent constructor using super() and verify that inherited properties are correctly initialized.

  8. Private Fields
    Create a class BankAccount with a private field #balance. Add methods to deposit money and check balance. Attempt to access #balance directly.

  9. Multiple Instances Sharing Methods
    Show that two instances of a class share the same method reference by comparing the function references.

  10. Computed Method Names
    Define a method in a class using a computed property name (e.g., [methodName]()) and call it on an instance to demonstrate dynamic method definition.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top