The JavaScript Arrow Function cannot be used to create an object. In this post, we will learn the reason behind that.
An Arrow Function Cannot be Used as a Constructor
Before we move ahead, you should know that JavaScript has three types of functions. They are:
- Function declaration
- Function expression
- Arrow function
JavaScript allows you to create an object from a function expression or a function declaration.
function Product(title, price){
this.title = title;
this.price = price;
}
let p1 = new Product("Pen",100);
console.log(p1);
Above, the p1 object uses Product function as a constructor.
console.log(p1.constructor); // [Function: Product]
Now, let us convert the Product function statement to an arrow function, as shown in the next code block:
let Product = (title, price) => {
this.title = title;
this.price = price;
}
let p1 = new Product("Pen",100);
JavaScript complains when you use the Product function to create an object.
To understand its reason, let us create two functions, one as a function declaration and another as an arrow function, and print the prototype property of these functions.
function Product(title, price){
this.title = title;
this.price = price;
}
console.log(Product.prototype) // {}
let Productf = (title, price) => {
this.title = title;
this.price = price; }
console.log(Productf.prototype); // undefined
As you see, the value of the prototype property of the Product function (function declaration) is an empty object. In contrast, the value of the prototype property of the Productf function (arrow function) is undefined.
The prototype property of an arrow function is undefined.
Next, let us understand why a function’s prototype property is essential to create an object. So, whenever you create an object using a function, that object is linked to the prototype object of the function.
function Product(title, price){
this.title = title;
this.price = price;
}
let p1 = new Product("Pen",100) ;
let p2 = new Product("Pencil", 300);
console.log(p1.constructor.prototype == p2.constructor.prototype); // true
Here, p1 and p2 objects are created from the Product function and are linked to the Product’s prototype object.
All objects created from a function are linked to the function’s prototype object.
As you have already seen, an arrow function does not have the prototype object; hence it cannot be used to create an object or, in other words, cannot be used as a constructor.
let Productf = (title, price) => {
this.title = title;
this.price = price;
}
console.log(Productf.prototype); // undefined
An arrow function:
- Does not have the prototype property
- Also does not have the internal [[Constructor]] property
For the above two reasons, an arrow function cannot create an object in JavaScript. I hope you find this post helpful. Thanks for reading.