Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Constructor Function & New Operatorin JavaScript

Javascript object Constructor function allows us to create multiple similar objects easily. We invoke the constructor function using the new operator. In this tutorial, let us learn what is a constructor function, how to create a constructor, how to create multiple objects using the constructor function, and the role of the new operator in invoking the constructor function.

What is a Constructor function?

The constructor function is a regular JavaScript function that contains a recipe to create a new object. When we invoke it using the new operator it creates a new instance of the object and returns it.

By Convention, we capitalize the first letter of the constructor function name. But that is optional and JavaScript does not care.

What is New Operator

The new operator lets us create and initializes a new object from a constructor function.

How to Create a Constructor function

We create a constructor function similar to the way in which we create functions in JavaScript.

The following is the example of a Constructor function Person. The function accepts three arguments. You can pass as many arguments or no arguments to the function

        
function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.fullName = function() {
    return this.firstName + ' ' + this.lastName;
  };
}
 
                
        
    

Inside the function, we create properties and assign them to the object pointed by this.

We invoke it with the new operator and passing the value for each parameter. It will create a new person object and returns it.

        
let person = new Person('Alex', 'Ferguson', 50);
console.log(person);
console.log(person.fullName());
 
                
        
    

How New Operator works

The new operator can be used on any function. For Example the following code works without any error.

        
function sayHello() {
  console.log("hi")
}
 
new sayHello();
 
                
        
    

But, when we invoke any function with the new keyword, it does the following things

  1. It creates an empty JavaScript object
  2. Adds the __proto__ Property to the object and links it to the constructor functions prototype property.
  3. Binds the this context of function to the newly created object.
  4. If the constructor function returns an object then new will return it. Else it will return this. If the function returns any primitive value, it will ignore it and returns this

In the following example, the newClone function shows what new operator does behind the scene

        
function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.fullName = function () {
    return this.firstName + ' ' + this.lastName;
  };
}
 
 
 
//This function mimics new operator
 
function newClone(ConstFunc, ...theArgs) {
 
  //1. Creates a new object
  let obj = {};
 
  //2. Sets prototype of constructor function as the prototype of newly created object
  Object.setPrototypeOf(obj, ConstFunc.prototype)
 
  //3. calls the ConstFunc using call and sets obj as its 'this'.
  let ret = ConstFunc.call(obj, ...theArgs)
 
  //4. if it returns Object then returns it as it is
  if (ret == Object) return ret
 
  //else return obj
  return obj;
}
 
//Person created using the NewClone
personclone  = newClone(Person, 'Alex', 'Ferguson', 50)
console.log(personclone );
 
//Person created using the new Operator
person = new Person('Alex', 'Ferguson', 50)
console.log(person);
                
        
    

You can compare both the objects. You will find that they are identical.

Creating Multiple Objects

Use a function, if you wish to create multiple objects using the same recipe. The following example creates two Person objects.

        
function person(firstName, lastName, age) {
 
    return { 
        firstName: firstName, 
        lastName: lastName, 
        age: age
    }
}
 
 
let allie=person("Allie","Grater",50)
let Paul=person("Paul","Molive",25)
 
console.log(allie)
console.log(Paul)
    
        
    

Creating Object without new

The following example shows how we can create a new object without using the new operator. This will also create a new object identical to one using the new operator.

        
function Person(firstName, lastName, age) {
  //Create an empty object
  let obj = {};
 
  //Assign properties & methods
  obj.firstName = firstName;
  obj.lastName = lastName;
  obj.age = age;
  obj.fullName = function() {
    return obj.firstName + ' ' + obj.lastName;
  };
 
  //Setting the prototype of newly created object
  Object.setPrototypeOf(obj, Person.prototype)
 
  //return it
  return obj;
}
 
let person = Person('Alex', 'Ferguson', 50);
console.log(person);
    
        
    

The use case for Constructor Functions

The constructor function makes it easier to create as many objects as you want, using the same pattern.

                            
let person1 = new Person('Alex', 'Ferguson', 50);
let person2 = new Person('Santi', 'Argo', 40);
let person3 = new Person('Sarah', 'Moanees', 25);
 
  
    
        
    

Built-in Objects

The JavaScript includes constructors for its built-in types. We can use the new keyword to instantiate them as shown below.

                            
// Create an empty object.
let o = new Object(); 
 
// Create an empty array
let a = new Array(); 
 
// Create a Date object representing
the current time
let d = new Date(); 
 
// Create a Map object for key/value 
mapping
let r = new Map(); 
 
  
    
        
    

Single Use constructors using new

        
let person = new function() {
  this.firstName = 'Barry';
  this.lastName = 'Kade';
}();
console.log(person);
 
 
    
        
    

Return from constructors

The constructor function returns this. Hence it is not common to have a return statement. But you can return any other object other than this then the new operator will use that

                        
function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.displayName = function() {
    return this.firstName + ' ' + this.lastName;
  };
 
  let obj = {};
  obj.firstName = 'Polly';
  obj.lastName = 'Pipe';
  return obj;
}
 
var person = new Person('Carmen', 'Sayid');
console.log(person);
 
***Console***
//{firstName: "Polly", lastName: "Pipe"}      

                                    
                                

But if you return a primitive data type like string, number, bigint, boolean, and symbol it is ignored and this is returned

                        
    function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.displayName = function() {
    return this.firstName + ' ' + this.lastName;
  };
 
  return '10';
}
 
var person = new Person('Carmen', 'Sayid');
console.log(person);
 
 
*** Console ****
Person {firstName: "Carmen", lastName: "Sayid", displayName: ƒ}     

                                    
                                

Constructor Example


function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.displayName = function() {
    return this.firstName + ' ' + this.lastName;
  };
}
 
function Car(make, model, owner) {
  this.make = make;
  this.model = model;
  this.owner = owner;
}
 
let Carmen = new Person('Carmen', 'Sayid');
let Polly = new Person('Polly', 'Pipe');
 
var Jeep = new Car('Jeep', 'Compass Sport', Carmen);
var Nissan = new Car('Nissan', '300ZX', Polly);
 
console.log(Jeep.owner.displayName());
console.log(Nissan.owner.displayName());