Constructor
This lesson explains Constructor with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.
ES6 Constructor Overview
A constructor is a special method inside an ES6 class that
automatically executes whenever a new object is created using the
new keyword.
Constructors initialize object properties, assign default values, validate input, prepare application state, and perform one-time setup for each object instance.
| Feature | Description |
|---|---|
| Purpose | Initialize newly created objects. |
| Runs Automatically | Yes, whenever new creates an object. |
| Constructor Count | Only one constructor is allowed per class. |
| Inheritance | Child constructors call super(). |
| Returns | Implicitly returns the new object. |
| Common Uses | Initialize state, configuration, services, models and UI components. |
Basic Constructor Example
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
const user =
new User(
"John",
"john@example.com"
);
console.log(user); The constructor initializes the object with values passed during object creation.
How Constructor Works
- The
newkeyword creates an empty object. - The constructor executes automatically.
thispoints to the new object.- Properties are assigned.
- The object is returned automatically.
const employee =
new Employee(
"Alice",
"Developer"
); Constructor Without Parameters
class Counter {
constructor() {
this.count = 0;
}
}
const counter =
new Counter();
console.log(counter.count); Constructors do not require parameters. They can initialize default values.
Constructor With Default Parameters
class User {
constructor(
name = "Guest",
role = "User"
) {
this.name = name;
this.role = role;
}
}
const user =
new User();
console.log(user); Initializing Multiple Properties
class Product {
constructor(
id,
name,
price,
stock
) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
} Constructor with Methods
class Student {
constructor(name) {
this.name = name;
}
greet() {
return "Hello " + this.name;
}
}
const student =
new Student("David");
console.log(
student.greet()
); Object Initialization Example
class Car {
constructor(
brand,
model,
year
) {
this.brand = brand;
this.model = model;
this.year = year;
}
}
const car =
new Car(
"Tesla",
"Model Y",
2025
); Using this Inside Constructor
class Employee {
constructor(name) {
this.name = name;
}
}
The this keyword refers to the current object being created.
Input Validation
class Account {
constructor(balance) {
if (balance < 0) {
throw new Error(
"Invalid balance."
);
}
this.balance = balance;
}
} Constructors are an excellent place to validate incoming data.
Constructor Creating Default Objects
class ShoppingCart {
constructor() {
this.items = [];
this.total = 0;
}
} Calling Other Methods
class User {
constructor(name) {
this.name = name;
this.initialize();
}
initialize() {
console.log(
"User initialized."
);
}
} Inheritance Constructor
class Person {
constructor(name) {
this.name = name;
}
}
class Employee
extends Person {
constructor(
name,
role
) {
super(name);
this.role = role;
}
}
Child classes must call super() before accessing
this.
Using super()
class Animal {
constructor(type) {
this.type = type;
}
}
class Dog
extends Animal {
constructor(name) {
super("Dog");
this.name = name;
}
} Only One Constructor Allowed
// Invalid
class User {
constructor() {}
constructor(name) {}
} JavaScript allows only one constructor per class.
Factory Method vs Constructor
class User {
constructor(name) {
this.name = name;
}
static guest() {
return new User("Guest");
}
}
const guest =
User.guest(); Constructor with Object Parameter
class User {
constructor(options) {
this.name =
options.name;
this.email =
options.email;
this.age =
options.age;
}
}
const user =
new User(
{
name: "John",
email: "john@example.com",
age: 25
}
); Passing an options object is preferred when there are many parameters.
Real World Example - API Client
class ApiClient {
constructor(baseUrl) {
this.baseUrl =
baseUrl;
}
getUsers() {
return fetch(
this.baseUrl + "/users"
);
}
}
const api =
new ApiClient("/api"); Real World Example - Configuration
class Config {
constructor(environment) {
this.environment =
environment;
this.timeout =
5000;
}
} Real World Example - UI Component
class Modal {
constructor(selector) {
this.element =
document.querySelector(
selector
);
}
open() {
this.element.hidden =
false;
}
} Real World Example - Form Model
class LoginForm {
constructor() {
this.username = "";
this.password = "";
}
} Constructor Best Practices
- Keep constructors small.
- Initialize only essential data.
- Validate incoming parameters.
- Use default parameter values.
- Prefer options objects for many parameters.
- Avoid complex business logic.
- Call helper methods when initialization becomes large.
- Keep constructors predictable.
- Always call
super()in child classes. - Use dependency injection when appropriate.
Common Constructor Mistakes
- Forgetting the
newkeyword. - Using multiple constructors.
- Accessing
thisbeforesuper(). - Putting API requests directly inside constructors.
- Creating huge constructors.
- Ignoring parameter validation.
- Passing too many positional arguments.
- Using constructors for unrelated work.
Constructor vs Regular Method
| Constructor | Regular Method |
|---|---|
| Runs automatically. | Called manually. |
| Initializes objects. | Performs operations. |
| Only one allowed. | Unlimited methods. |
Called by new. | Called by object.method(). |
| Creates initial state. | Updates existing state. |
Constructor Interview Questions
- What is a constructor?
- When is a constructor executed?
- Can a class have multiple constructors?
- Why is
super()required? - Why use an options object?
- What is the purpose of
this? - Can constructors return objects?
- What happens if
newis omitted? - When should business logic be avoided inside constructors?
- How are constructors different from factory methods?
Pro Tip
Keep constructors focused on object initialization only. Expensive operations such as API requests, file loading, database calls, or complex calculations should usually be placed in separate methods instead of the constructor. Small constructors are easier to understand, test, and maintain.