Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a default constructor in JavaScript?
In JavaScript classes, if you don't define a constructor method, the JavaScript engine automatically provides a default constructor. This default constructor is implicit and handles basic object initialization.
What is a Default Constructor?
A default constructor is an empty constructor that JavaScript creates automatically when no explicit constructor is defined in a class. It performs minimal initialization and, for derived classes, calls the parent constructor.
Syntax
For base classes, the default constructor is equivalent to:
constructor() {}
For derived classes (classes that extend another class), the default constructor is:
constructor(...args) {
super(...args);
}
Example: Base Class with Default Constructor
class Person {
// No constructor defined - default constructor is used
greet() {
console.log("Hello from Person");
}
}
const person = new Person();
person.greet();
console.log("Person created successfully");
Hello from Person Person created successfully
Example: Derived Class with Default Constructor
class Animal {
constructor(name) {
this.name = name;
console.log(`Animal ${name} created`);
}
}
class Dog extends Animal {
// No constructor defined - default constructor calls super()
bark() {
console.log(`${this.name} says woof!`);
}
}
const dog = new Dog("Buddy");
dog.bark();
Animal Buddy created Buddy says woof!
Comparison: Default vs Explicit Constructor
| Constructor Type | When Used | Functionality |
|---|---|---|
| Default Constructor | No constructor defined | Basic initialization, calls super() for derived classes |
| Explicit Constructor | Constructor method defined | Custom initialization logic |
Key Points
- Default constructors are automatically provided when no constructor is defined
- They perform minimal initialization without custom logic
- For derived classes, they automatically pass all arguments to the parent constructor
- You cannot access the default constructor explicitly - it's handled internally
Conclusion
Default constructors provide automatic object initialization when no explicit constructor is needed. They ensure proper inheritance behavior by calling the parent constructor in derived classes.
