Adding Class in JavaScript: A Comprehensive Guide

JavaScript has evolved significantly over the years, and one of the most important features introduced in ES6 (ECMAScript 2015) is the class syntax. This guide will walk you through everything you need to know about adding classes in JavaScript, including their syntax, methods, constructors, and inheritance.

What is a Class in JavaScript?

A class is a blueprint for creating objects. It defines a set of properties and methods that the objects created from the class (called instances) will have. Before ES6, JavaScript used prototypes to create objects, but classes provide a more intuitive and cleaner syntax.

Syntax of a Class

The basic syntax for defining a class in JavaScript is as follows:

// Define a class called 'Car'
class Car {
  // Constructor method
  constructor() {
    // Initialization code
  }

  // Regular method
  start() {
    console.log('Car started');
  }
}

Creating an Instance of a Class

Once a class is defined, you can create an instance of it using the new keyword:

const myCar = new Car();
myCar.start(); // Output: 'Car started'

Class Constructors

The constructor method is a special method that is called when an instance of the class is created. It is typically used to initialize the object’s properties.

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

const john = new Person('John', 'Doe');
console.log(john.firstName); // Output: 'John'

Default Parameters in Constructors

You can also use default parameters in the constructor:

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

const person = new Person();
console.log(person.firstName); // Output: 'Unknown'

Adding Methods to a Class

Methods are functions defined inside a class. They can be instance methods (called on instances) or static methods (called on the class itself).

Instance Methods

class Calculator {
  constructor() {
    this.result = 0;
  }

  add(number) {
    this.result += number;
  }
}

const calc = new Calculator();
calc.add(5);
console.log(calc.result); // Output: 5

Static Methods

Static methods are defined using the static keyword and are called on the class, not on instances.

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

console.log(MathUtils.add(3, 4)); // Output: 7

Class Inheritance

JavaScript classes support inheritance using the extends keyword. You can create a subclass that inherits properties and methods from a parent class.

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

  speak() {
    console.log('The animal makes a sound');
  }
}

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

  speak() {
    console.log('Bark!');
  }
}

const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.name); // Output: 'Buddy'
myDog.speak(); // Output: 'Bark!'

Getters and Setters

You can define getters and setters in a class to control access to properties.

class User {
  constructor(email) {
    this._email = email;
  }

  get email() {
    return this._email;
  }

  set email(value) {
    this._email = value.toLowerCase();
  }
}

const user = new User('[email protected]');
console.log(user.email); // Output: '[email protected]'

user.email = '[email protected]';
console.log(user.email); // Output: '[email protected]'

Frequently Asked Questions

1. What is the difference between a class and an object?

A class is a blueprint for creating objects, while an object is an instance of a class. The class defines the properties and methods that the object will have.

2. Can I create a class without a constructor?

Yes, if you don’t define a constructor, JavaScript will automatically create a default constructor with no parameters.

3. How do I inherit from a class?

You use the extends keyword to create a subclass that inherits from a parent class. The super keyword is used to call the parent class’s constructor.

4. What are static methods used for?

Static methods are used when you want a method to be called on the class itself rather than on an instance. They are often used for utility functions.

5. Can I have private properties in a class?

Yes, you can define private properties using the # symbol before the property name. These properties are only accessible within the class.

class BankAccount {
  #balance;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

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

const account = new BankAccount(1000);
console.log(account.getBalance()); // Output: 1000
console.log(account.#balance); // Error: Private property '#balance' is not accessible

Conclusion

Classes in JavaScript provide a clean and intuitive way to create objects and manage inheritance. With features like constructors, methods, static methods, and getters/setters, classes make it easier to organize and structure your code. By following this guide, you should now be comfortable with defining and using classes in your JavaScript projects.

Index
Scroll to Top