JavaScript Constructor: The Simplest Way to Build Objects
See how a JavaScript constructor works in its simplest form: define a class, pass in a value, and create a new object with new.


What Is a JavaScript Constructor?
If you haven’t read our article on class usage in our previous JavaScript lessons yet, I recommend reading it before starting this article. Now let’s get to using constructors in JavaScript. A constructor is a function that is called when a new instance of a class is created. This function—the constructor function—is used to set the class’s properties and initial values inside the class.
In JavaScript, the constructor function is defined inside the class with the constructor keyword. The constructor function is called automatically when a new instance of the class is created and sets the instance’s properties. To recall the example we used in our previous example, let’s write a similar one again and examine it.
class Araba {
// Properties
marka;
model;
renk;
// Constructor function
constructor(marka, model, renk) {
this.marka = marka;
this.model = model;
this.renk = renk;
}
}
const araba1 = new Araba("Toyota", "Corolla", "siyah");
const araba2 = new Araba("Ford", "Mustang", "kırmızı");
We reused the example we wrote in our previous article here to make it clearer. In this example, the Araba class was created and its marka, model and renk properties were set with the constructor function. Finally, two car objects named araba1 and araba2 were created.
As you can see in the example, the Constructor function is called automatically when a new instance of the class is created and sets the instance’s properties. For example, the araba1 object’s marka property was set to “Toyota”, its model property to “Corolla” and its renk property to “siyah”, and we got a result. You can reinforce the topic further by preparing similar examples.
Share it if it helped


