← Back to JavaScript Course | Chapter 4: Modern JS, Async & DOM | Lesson 14 of 26

JS Classes

Think of an architectural blueprint for a house, the blueprint itself isn't a house you can live in, but it defines exactly how to build one, and you can use that same blueprint to construct many individual houses, each with its own address but the same layout. A class in JavaScript is that blueprint, a template describing what properties and methods every object built from it will have, and each individual object created from a class is called an instance. Classes help organize larger applications, like modeling a Tutorial or a User consistently across a codebase powering something like cookiescursor.com.
Syntax
javascript
class ClassName {
  constructor(parameter) {
    this.property = parameter;
  }
  methodName() {
    // body
  }
}

const object = new ClassName(argument);

Class Syntax and the Constructor

A class is declared with the class keyword, and its constructor method runs automatically whenever a new instance is created with new, typically used to set up the instance's initial properties.

Note: The constructor is the natural place to accept parameters and assign them to this, establishing each instance's starting state.
Warning: A class can only have one constructor method, defining a second one causes a syntax error.

उदाहरण: Class Syntax and the Constructor

javascript
// Define the class `User`
// Define the class `User`
class User {
  // Constructor taking `name`, runs when a new instance is created
  // Constructor taking `name`, runs when a new instance is created
  constructor(name) {
    // Assign `name` to `this.name`
    // Assign `name` to `this.name`
    this.name = name;
  }
}
// Declare the constant `u` as a new `User` instance
// Declare the constant `u` as a new `User` instance
const u = new User("Sam");
// Print `u.name` to the console
// Print `u.name` to the console
console.log(u.name);

Methods

Methods defined inside a class become available on every instance created from it, letting each object built from the class share the same behavior without duplicating that code.

Note: Class methods are written without the function keyword, similar to shorthand methods in object literals.
Warning: Methods defined on a class are shared across all instances, they cannot access instance-specific data unless referenced through this.

उदाहरण: Methods

javascript
// Define the class `User`
// Define the class `User`
class User {
  constructor(name) { this.name = name; }
  greet() { console.log(`Hi, ${this.name}`); }
}
// Create a new `User` instance with `"Amit").greet(`
// Create a new `User` instance with `"Amit").greet(`
new User("Amit").greet();

Inheritance With extends and super

extends lets one class build on another, inheriting its properties and methods, and super() inside a subclass's constructor calls the parent class's constructor, which must run before this can be used.

Note: A subclass can override a parent method simply by defining a method with the same name, while still calling super.methodName() if it needs the original behavior too.
Warning: Forgetting to call super() as the very first line in a subclass constructor throws a ReferenceError before this can even be used.

उदाहरण: Inheritance With extends and super

javascript
// Define the class `Animal`
// Define the class `Animal`
class Animal {
  constructor(name) { this.name = name; }
}
// Define the class `Dog`, inheriting from `Animal`
// Define the class `Dog`, inheriting from `Animal`
class Dog extends Animal {
  // Constructor taking `name`, runs when a new instance is created
  // Constructor taking `name`, runs when a new instance is created
  constructor(name) {
    // Call `super(name)`
    // Call `super(name)`
    super(name);
  }
  bark() { console.log(`${this.name} says woof`); }
}
// Create a new `Dog` instance with `"Rex").bark(`
// Create a new `Dog` instance with `"Rex").bark(`
new Dog("Rex").bark();

Static Methods

A static method belongs to the class itself rather than to individual instances, called directly on the class name, and is commonly used for utility functions closely related to the class but not tied to any specific instance's data.

Note: Static methods are a natural home for factory-style functions that create and return new instances of the class.
Warning: A static method cannot access this to reach instance properties, since it's never called on an actual instance.

उदाहरण: Static Methods

javascript
// Define the class `MathUtil`
// Define the class `MathUtil`
class MathUtil {
  static double(n) { return n * 2; }
}
// Print `MathUtil.double(5)` to the console
// Print `MathUtil.double(5)` to the console
console.log(MathUtil.double(5));

Getters and Setters

get and set define special methods that run automatically when a property is read or assigned, letting you compute a derived value on read or validate a value before it's stored, while the calling code still uses ordinary property syntax.

Note: Getters are great for computed properties, like combining a first and last name, without storing that combination as a separate, duplicated field.
Warning: A getter and setter with the same name should not directly read or write that identical name inside themselves, doing so causes infinite recursion.

उदाहरण: Getters and Setters

javascript
// Define the class `Circle`
// Define the class `Circle`
class Circle {
  constructor(radius) { this._radius = radius; }
  get area() { return Math.PI * this._radius ** 2; }
  set radius(value) { this._radius = value; }
}
// Declare the constant `c` as a new `Circle` instance
// Declare the constant `c` as a new `Circle` instance
const c = new Circle(2);
// Print `c.area` to the console
// Print `c.area` to the console
console.log(c.area);
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.