JavaScript constructor

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

The constructor method runs once when you new a class. Use it to set up this. A class may have only one constructor.

JavaScript Syntax

JavaScript
class Counter {
  constructor(start) {
    this.value = start;
  }
}
console.log(new Counter(5).value);
Try it Editor

How It Works

  1. new Counter(5). Passes 5 into constructor.
  2. this.value. Stored on the instance.

Examples

Example 1 — Default parameters

Constructors accept defaults.

JavaScript
class C { constructor(n = 0){ this.n = n; } }
console.log(new C().n);
Try it Editor

How It Works

  1. Missing arg uses 0.

Example 2 — Returning an object

Rare: constructor can return another object.

JavaScript
class C { constructor(){ return { ok: true }; } }
console.log(new C().ok);
Try it Editor

How It Works

  1. Returned object replaces the default instance.

Example 3 — Need super in subclass

Call before using this.

JavaScript
class A { constructor(){ this.a = 1; } }
class B extends A { constructor(){ super(); this.b = 2; } }
console.log(new B().a, new B().b);
Try it Editor

How It Works

  1. super() runs parent constructor.

Frequently Asked Questions

Yes. A default empty constructor is provided (and subclasses get one that calls super(...args)).

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful