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.

javascript
1function User(name) {
2  this.name = name;
3  this.role = "Visitor";
4}
5
6let john = User("John");
7console.log(john);
text
1undefined

The constructor function can also be used to create methods. For example:

javascript
1function User(firstName, lastName) {
2  this.firstName = firstName;
3  this.lastName = lastName;
4
5  this.printFullName = function () {
6    console.log(`${this.firstName} ${this.lastName}`);
7  };
8}
9
10let john = new User("John", "Doe");
11
12console.log(john);
13console.log(john.firstName);
14console.log(john.lastName);
15john.printFullName();

The constructor offers a great deal of flexibility when creating objects with similar structures.

At this point, this syntax should look familiar to you, because we've seen it many times. For example, we used the same keyword new to create an array,

javascript
1let arr = new Array("Apple", "Orange", "Banana");

A map,

javascript
1let map = new Map([
2  ["Apple", 5],
3  ["Orange", 6],
4  ["Banana", 7],
5]);

And a set,

javascript
1let set = new Set([1, 2, 3, 4, 3, 2, 1]);

Array(), Map(), and Set() are also constructor functions that are built into JavaScript, and this is another proof that arrays, maps, and sets are just special variants of objects.