DEV Community

Sosanya Esther
Sosanya Esther

Posted on • Edited on

Constructors in JavaScript

The Javascript Set Constructor is used to create Set objects. It will create a set of unique values of any type, whether primitive values or object preferences.
A constructor is useful when you want to create multiple similar objects with the same properties and methods. It’s a convention to capitalize the name of constructors to distinguish them from regular functions.

Image description
The last line of the code creates an instance of Book and assigns it to a variable. Although the Book constructor doesn’t do anything, myBook is still an instance of it. As you can see, there is no difference between this function and regular functions except that it’s called with the new keyword and the function name is capitalized.

A constructor is a function that executes the initialization of an object when the object is created. Arguments are passed to the constructor function when you use the new keyword.
There are two types of constructors, one defined as a function, and one defined with the constructor method in a class.

The Object Constructor Function:
To use a constructor function to create objects, simply define a JavaScript function with any number of arguments. Inside the function, the keyword this is used as a placeholder for the object being created. If the constructor function is used by itself, without the new statement, this will have no value.
It’s preferred to capitalize a constructor function.

Image description

The Class constructor Method:
When defining a class in JavaScript, there is a special constructor method defined within it. Like the object constructor function, the constructor method can be defined with any number of arguments, and the this keyword can be used as a placeholder for the object being created.

Image description

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series