What Are Constructor Functions in JavaScript

A constructor function is a special type of function that allows you to programmatically create objects.

javascript
1function User(name) {
2  this.name = name;
3  this.role = "Visitor";
4}

Constructor functions are just regular functions, except it is conventional for them to be named with uppercase letters.

And when calling the constructor functions, you must use the keyword new, which tells JavaScript that this is a constructor function, not a regular function.

javascript
1let john = new User("John");
2
3console.log(john);
text
1User { name: 'John', role: 'Visitor' }

Even though we did not write a return statement, a new object will be returned, which is then assigned to the variable john, and you can modify it like a regular object.

javascript
1let john = new User("John");
2console.log(john);
3
4john.role = "Admin";
5console.log(john);
text
1User { name: 'John', role: 'Visitor' }
2User { name: 'John', role: 'Admin' }

Without the keyword new, the function will be executed like a regular function, and undefined will be returned.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉