No, arrow functions cannot be used as constructors. They don’t have the internal [[Construct]] property, which is necessary for working with the [new] keyword. Moreover, arrow functions don’t have their own [this], making them unsuitable for creating objects.
// ❌ This doesn't work
const User = (name) => {
this.name = name;
};
// new User('John'); // TypeError: User is not a constructor
// ✅ This is correct
function User(name) {
this.name = name;
}
const user = new User('John');
console.log(user.name); // 'John'Arrow functions are like lazy workers who don’t want to take responsibility for creating something new. They can’t be constructors, and the reason is very simple! 🚫
Arrow functions are simplified functions that lack some important capabilities of regular functions:
// Regular functions have [[Construct]] property
function RegularFunction() {}
new RegularFunction(); // Works
// Arrow functions don't have it
const ArrowFunction = () => {};
// new ArrowFunction(); // TypeError!// Regular constructor function
function User(name) {
this.name = name; // this — new object
}
// Arrow function
const UserArrow = (name) => {
this.name = name; // this is taken from outer scope!
};
// new UserArrow('John'); // Error!const Car = (brand) => {
this.brand = brand;
};
// ❌ Doesn't work
// const myCar = new Car('Toyota'); // TypeError: Car is not a constructor// ✅ Regular function as constructor
function Car(brand) {
this.brand = brand;
}
const myCar = new Car('Toyota');
console.log(myCar.brand); // 'Toyota'function User(name) {
this.name = name;
}
// new User('John') does:
// 1. Creates empty object {}
// 2. Sets this = {}
// 3. Executes function code
// 4. Returns thisconst User = (name) => {
this.name = name;
};
// new User('John') can't:
// ❌ No [[Construct]] property
// ❌ No own this
// ❌ Can't create new objectconst add = (a, b) => a + b;
const numbers = [1, 2, 3].map(n => n * 2);const obj = {
name: 'John',
friends: ['Peter', 'Mary'],
showFriends() {
this.friends.forEach(friend => {
console.log(this.name + ' is friends with ' + friend);
});
}
};function Product(name, price) {
this.name = name;
this.price = price;
}
const product = new Product('Book', 500);const calculator = {
value: 0,
add(num) {
this.value += num;
return this;
}
};// ❌ Common mistake
const CreateUser = (name) => {
this.name = name;
};
// new CreateUser('John'); // TypeError!
// ✅ Correct solution
function CreateUser(name) {
this.name = name;
}
new CreateUser('John'); // Works!// ❌ Syntax error
// new (name => { this.name = name })('John');
// ✅ Correct syntax for constructor function
new function(name) { this.name = name; }('John');Arrow functions are good for simple tasks, but not suitable for creating objects. Regular functions are needed for that! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪