A function used to generate new objects in JavaScript is called a constructor function. It creates new objects, which is why it is known as a constructor.
The function keyword is used to create a constructor function in JavaScript. The function name ought to be illustrative of the kind of object that it will produce. A Person object’s constructor function, for instance, might be called Person.
The code that is run when a new object is formed should be in the constructor function’s body. You can use this code to set the new object’s properties to their initial values.
A constructor function in JavaScript that generates a Person object is demonstrated here:
<script type="text/javascript">
function Person(person_name, person_age, person_gender) {
// assigning parameter values to the calling object
this.name = person_name,
this.age = person_age,
this.gender = person_gender,
this.greet = function() {
return ('Hi' + ' ' + this.name);
}
}
// creating objects
const person1 = new Person('abhishek', 25, 'male');
const person2 = new Person('akash', 25, 'male');
// accessing properties
console.log(person1.name);
console.log(person2.name);
</script>

I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] https://www.devopsconsulting.in/blog/use-constructor-function-in-javascript/ […]