Sub topic 10
Arrow Functions Cannot Be Constructors
This chapter assumes you can already write arrow functions and regular functions, and that you know how this works in each, as covered in the earlier chapters. You should also know that objects can inherit properties through a prototype, though you don't need to know the details of prototype chains.
You can call any function, but only some functions can be called with new. Arrow functions are not among them. This chapter explains what new actually needs from a function, why arrows don't provide it, and which other function forms are also not constructors.
The Short Version
A regular function can be used as a constructor. An arrow function throws a TypeError as soon as you try:
function Person(name) {
this.name = name;
}
const ArrowPerson = (name) => {
this.name = name;
};
console.log(new Person('Ada').name); // Ada
console.log(ArrowPerson.prototype); // undefined
try {
new ArrowPerson('Ada');
} catch (e) {
console.log(e instanceof TypeError); // true
}In V8 (Node.js and Chrome), the message reads TypeError: ArrowPerson is not a constructor. The error is thrown before the body runs, so this.name = name never executes.
This example shows two differences:
ArrowPerson.prototypeisundefined. Regular functions get aprototypeobject automatically. Arrows do not.new ArrowPerson(...)throws. The engine checks whether the function can be constructed before doing anything else.
What `new` Needs From a Function
The specification gives each function object a set of internal methods. Every function has [[Call]], which runs it as an ordinary call. Constructible functions also have [[Construct]], which runs when you use new. Arrow functions are created without [[Construct]], and that missing internal method is the whole reason for the error.
When [[Construct]] exists, new F(...args) does roughly this:
- Check that
Fis a constructor. If not, throwTypeError. - Create a new empty object whose prototype is
F.prototype. - Run the body of
Fwiththisset to that new object. - If the body returns an object, use it. Otherwise, use the new object.
An arrow fails at the first step. Even if it passed, steps 2 and 3 would still not work for it. You can see this by writing a simplified version of new by hand:
function myNew(Ctor, ...args) {
const obj = Object.create(Ctor.prototype);
const result = Ctor.apply(obj, args);
const isObject =
result !== null && (typeof result === 'object' || typeof result === 'function');
return isObject ? result : obj;
}
function Person(name) {
this.name = name;
}
const ArrowPerson = (name) => {
return name;
};
console.log(myNew(Person, 'Ada').name); // Ada
try {
myNew(ArrowPerson, 'Ada');
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message.includes('prototype') || e.message.length > 0); // true
}The hand-written version breaks in two places for an arrow:
Object.create(undefined)throws, because an arrow has noprototypeto inherit from.Ctor.apply(obj, args)would ignoreobjanyway. An arrow takesthisfrom its surrounding scope, andcall,apply, andbindcannot change it. The body could never reach the new object.
So the missing [[Construct]] is not an arbitrary rule. An arrow has no way to receive a fresh this, so construction could not work for it. The language makes that explicit by refusing new up front.
`new.target` Inside Arrows
Regular functions can read new.target to find out whether they were called with new. Arrows don't have their own new.target. Like this and arguments, they read it from the nearest enclosing regular function:
function Widget() {
const getTarget = () => new.target;
this.calledWithNew = getTarget() === Widget;
}
console.log(new Widget().calledWithNew); // trueThe arrow getTarget reports the new.target of Widget, not its own. If an arrow that uses new.target is not inside any regular function (for example, at the top level of a module), the code is a SyntaxError and the file will not load.
Which Function Forms Are Constructors
Arrows are not the only functions without [[Construct]]. Several newer forms were also designed to be called but not constructed.
| Function form | Can use `new` | Has own `prototype` property |
|---|---|---|
| Function declaration or expression | Yes | Yes |
| Class | Yes (and it must be called with `new`) | Yes |
| Arrow function | No | No |
| Method shorthand, `{ m() {} }` | No | No |
| Class method, getter, or setter | No | No |
| Async function | No | No |
| Generator function | No | Yes |
| Bound function, `f.bind(x)` | Only if `f` is a constructor | No |
| Most built-in functions, such as `Math.max` | No | No |
Two rows deserve a closer look:
- Generator functions have a
prototypeproperty but are still not constructors. Theirprototypeis used as the prototype for the generator objects they return. So checkingfn.prototypedoes not tell you whetherfnis a constructor. - Bound functions have no
prototypeproperty, butnewstill works on them when the original function is a constructor. In that casenewignores the boundthisand uses the original function'sprototype.
Testing Whether a Function Is a Constructor
Because prototype is not a reliable signal, use a check that asks the engine directly. Reflect.construct(target, args, newTarget) throws a TypeError if newTarget is not a constructor. Passing a harmless built-in as target gives you a test that never runs the function you are checking:
function isConstructor(fn) {
try {
Reflect.construct(String, [], fn);
return true;
} catch {
return false;
}
}
function Regular() {}
class Klass {}
const arrow = () => {};
const obj = { method() {} };
async function asyncFn() {}
function* gen() {}
console.log(isConstructor(Regular)); // true
console.log(isConstructor(Klass)); // true
console.log(isConstructor(arrow)); // false
console.log(isConstructor(obj.method)); // false
console.log(isConstructor(asyncFn)); // false
console.log(isConstructor(gen)); // false
console.log(isConstructor(Regular.bind(null))); // true
console.log(isConstructor(Math.max)); // false
console.log(gen.prototype !== undefined); // truefn is used only as newTarget, so its body never runs. The test has no side effects.
Common Mistakes
Writing a Constructor as an Arrow
Developers used to writing everything as const x = () => {} sometimes do the same for a constructor. The error shows up the first time the code calls new, which may be far from where the function is defined. The fix is to use a class or a regular function.
Putting Arrows on a Prototype
A subtler mistake is to leave the constructor as a regular function but write its shared methods as arrows:
function Person(name) {
this.name = name;
}
Person.prototype.whoRegular = function () {
return this;
};
Person.prototype.whoArrow = () => this;
const ada = new Person('Ada');
console.log(ada.whoRegular() === ada); // true
console.log(ada.whoArrow() === ada); // falseNo error is thrown here. The arrow took this from the scope where it was defined (module or script top level), so every instance gets the same wrong this. Methods on a prototype need their own dynamic this, so they should be regular functions or class methods.
Trusting Transpiled Output
Older build setups compile arrows into regular function expressions so they run in old browsers. Depending on the settings, the compiled function may not reject new, so code that calls new on an arrow can seem to work in a legacy bundle and then throw TypeError when it runs natively. Test against native output, or use a linter rule that flags new on values defined as arrows.
What to Use Instead
If you want arrow-style code that creates objects, write a factory function. A factory is an ordinary function that builds and returns an object, so it needs no new:
const makePoint = (x, y) => ({
x,
y,
length() {
return Math.hypot(this.x, this.y);
}
});
const p = makePoint(3, 4);
console.log(p.length()); // 5Use a class when you need what a constructor gives you:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const q = new Point(3, 4);
console.log(q.length()); // 5
console.log(q instanceof Point); // true| Need | Prefer |
|---|---|
| `instanceof` checks | Class |
| Methods shared on one prototype instead of copied into every object | Class |
| Inheritance with `extends` and `super` | Class |
| Plain data objects with no identity checks | Factory (arrow or regular) |
| Hiding the creation details, or returning different object shapes | Factory |
Exercise
What does this code log, and why? const Box = (v) => { this.v = v; }; console.log(typeof Box.prototype); try { new Box(1); } catch (e) { console.log(e.constructor.name); }
Show answer
It logs "undefined" and then "TypeError". Arrow functions get no prototype property, and they have no [[Construct]] internal method, so new throws a TypeError before the body runs.
Exercise
A teammate says "a function is a constructor if and only if fn.prototype is defined." Give one counterexample in each direction.
Show answer
A generator function such as function* g() {} has a prototype property but throws a TypeError when used with new. A bound function such as Regular.bind(null) has no prototype property but can be used with new when Regular is a constructor.
Exercise
You define function Car(make) { this.make = make; } and Car.prototype.describe = () => A ${this.make}; Why does new Car('Volvo').describe() not return "A Volvo", and how do you fix it?
Show answer
The arrow takes this from the scope where it was defined, not from the Car instance, so this.make is not the car's make. Write describe as a regular function (Car.prototype.describe = function () { return A ${this.make}; }) or convert Car to a class with a describe() method.