Sub topic 15
When instanceof Breaks: ES5 Transpilation
The earlier chapters used instanceof to tell errors apart in catch blocks. That works in any modern engine running native class syntax. It can stop working without any warning when a build tool compiles your classes down to ES5. ES5 is the JavaScript version from before class existed. This chapter explains why that happens, how to detect it, and how to fix it.
This chapter assumes you know ES2015 class syntax (extends, super), how prototypes and instanceof relate, and that you have used a compiler such as TypeScript or Babel at least once.
The Symptom
You write a custom error and a handler that checks for it:
class LegacyError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'LegacyError';
}
describe() {
return `${this.name}: ${this.message}`;
}
}
try {
throw new LegacyError('boom');
} catch (err) {
if (err instanceof LegacyError) {
console.log('handled:', err.describe());
} else {
throw err;
}
}Run as native JavaScript, this prints handled: LegacyError: boom. Compile it with TypeScript using "target": "ES5" and the output changes. The instanceof LegacyError check returns false, so the error falls through to throw err. If you call err.describe() directly, you get TypeError: err.describe is not a function. In both cases err.name is still 'LegacyError' and err instanceof Error is still true. That makes the bug hard to see in logs, because the output looks correct.
Why It Happens: Error Ignores `this`
ES5 has no class keyword, so a compiler turns your class into a constructor function. It implements super(...) by calling the parent constructor as a plain function. The following code reproduces the shape of TypeScript's ES5 output by hand, so you can run it in any engine:
function LegacyError(message, options) {
// How `super(message, options)` is compiled for an ES5 target
var _this = Error.call(this, message, options) || this;
_this.name = 'LegacyError';
return _this;
}
LegacyError.prototype = Object.create(Error.prototype, {
constructor: { value: LegacyError, writable: true, configurable: true },
});
LegacyError.prototype.describe = function () {
return this.name + ': ' + this.message;
};
var err = new LegacyError('boom');
console.log(err instanceof LegacyError); // false
console.log(err instanceof Error); // true
console.log(err.name); // 'LegacyError'
console.log(Object.getPrototypeOf(err) === Error.prototype); // true
console.log(typeof err.describe); // 'undefined'The key line is Error.call(this, message, options). With most constructor functions, Parent.call(this) initializes the object that this points to. Error behaves differently. When you call it as a function, it ignores this and returns a brand-new Error object. The language specification defines Error(...) and new Error(...) to do the same thing. Array, Map, and the other built-ins also refuse to initialize an object they did not create.
The compiled code keeps that returned object as _this. It sets name on it and returns it from the constructor. When a constructor returns an object, new returns that object in place of the one it allocated. So the caller receives an object whose prototype is Error.prototype, not LegacyError.prototype.
instanceof walks the prototype chain of the left operand and looks for LegacyError.prototype. That object is not in the chain, so the check fails. Everything defined on the subclass prototype is also missing, including methods and getters. Own properties set in the constructor, such as name, status, or code, do survive, because the constructor sets them directly on the returned object.
What Survives and What Breaks
| Feature of the subclass | ES2015+ target | ES5 target without fix |
|---|---|---|
| `err instanceof Error` | works | works |
| `err instanceof LegacyError` | works | `false` |
| `err instanceof` a parent custom class | works | `false` |
| Fields set in the constructor (`name`, `status`) | present | present |
| Prototype methods and getters | present | missing |
| `err.constructor` | `LegacyError` | `Error` |
| `message`, `stack`, `cause` | correct | correct |
The cause row deserves a note. The ES5 output passes options through to Error.call. A modern engine running that output still sets cause on the returned object. On an old engine that predates ES2022, the options argument is ignored and cause never appears.
The Fix: Restore the Prototype
The usual fix resets the prototype of the object after the super call:
class LegacyError extends Error {
constructor(message, options) {
super(message, options);
Object.setPrototypeOf(this, new.target.prototype);
this.name = 'LegacyError';
}
}In native code, this line does nothing harmful, because the prototype is already correct. In ES5 output, this compiles to _this, the object that Error returned, and the line relinks it to the right prototype. TypeScript also compiles new.target for ES5. It captures this.constructor before the super call, while this still refers to the object that new allocated. Hand-written, the fixed output looks like this:
function LegacyError(message, options) {
var _newTarget = this.constructor;
var _this = Error.call(this, message, options) || this;
Object.setPrototypeOf(_this, _newTarget.prototype);
_this.name = 'LegacyError';
return _this;
}
LegacyError.prototype = Object.create(Error.prototype, {
constructor: { value: LegacyError, writable: true, configurable: true },
});
var err = new LegacyError('boom');
console.log(err instanceof LegacyError); // true
console.log(err instanceof Error); // trueWhy `new.target` and Not the Class Name
TypeScript's own documentation shows Object.setPrototypeOf(this, LegacyError.prototype) with the class name hard-coded. That works for a single class and breaks hierarchies. new.target refers to the constructor that new was actually called with, so a base class can fix the prototype once for all of its subclasses:
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
Object.setPrototypeOf(this, new.target.prototype);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource, options) {
super(404, `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
const err = new NotFoundError('User 42');
console.log(err instanceof NotFoundError); // true
console.log(err instanceof HttpError); // trueIf HttpError hard-coded HttpError.prototype, every NotFoundError compiled to ES5 would be relinked to HttpError.prototype. instanceof NotFoundError would then return false. Fixing that would require repeating the line in every subclass.
How the Main Toolchains Behave
| Toolchain and setting | Does `instanceof` work without the fix? |
|---|---|
| No compilation, modern engine | Yes |
| TypeScript, `target` ES2015 or later | Yes, classes are emitted natively |
| TypeScript, `target` ES5 or ES3 | No |
| Babel 7, `@babel/plugin-transform-classes` | Usually yes. Babel detects direct subclasses of global built-ins and wraps them with a helper that uses `Reflect.construct` when the engine has it |
| Babel 6 | No, it needed a separate plugin |
| esbuild, SWC with ES2015+ target | Yes |
Babel's detection is based on syntax. It recognizes extends Error written against the global name. It may not recognize a built-in reached through an alias, such as const Base = Error; class X extends Base {}. On engines without Reflect.construct, the helper falls back to the broken behavior. A simple rule covers every case: if any of your build targets is ES5, add the setPrototypeOf line to your base error class.
The best fix is often to stop targeting ES5. Every browser that still receives security updates supports ES2015 classes. Raising TypeScript's target to "ES2015" or later (for example "ES2022", which also emits cause natively) removes the problem entirely. Check what your bundler and test runner do as well. A library might compile to ES2020 while your test setup recompiles it to ES5, so a test can fail even though production works.
Other Ways instanceof Fails
Transpilation is one of several reasons instanceof can fail, and the prototype fix only solves that one. Two other causes look similar:
- Multiple realms. An error thrown inside an iframe, a Node.js
vmcontext, or some worker setups was built from a different globalError. Its chain points to that realm'sError.prototype, soerr instanceof Errorisfalsein your realm. - Duplicate package copies. If two versions of a library are installed, each defines its own
NotFoundErrorclass. An error from copy A failsinstanceofagainst the class from copy B.
When errors cross these boundaries, branch on data rather than identity. Check err.name, or better, a stable code field like the ones added in the chapter on structured fields. The last chapter returns to this trade-off.
Exercise
A TypeScript project with "target": "ES5" defines class ApiError extends Error with a constructor that sets this.code. A catch block checks err instanceof ApiError, and the check fails, yet logs show err.code is set correctly. Explain why the field survives while instanceof fails.
Show answer
For ES5, super(...) compiles to Error.call(this, ...). Error ignores this and returns a new object whose prototype is Error.prototype. The compiled constructor keeps that object as _this, sets code on it, and returns it. Own properties assigned in the constructor therefore end up on the returned object, but its prototype chain never includes ApiError.prototype, so instanceof ApiError is false.
Exercise
A base class AppError fixes its prototype with Object.setPrototypeOf(this, AppError.prototype). A subclass AuthError extends AppError adds no fix of its own. Under an ES5 target, what do err instanceof AuthError and err instanceof AppError return for new AuthError(), and how do you correct it with a single change?
Show answer
err instanceof AppError is true, but err instanceof AuthError is false, because the base constructor relinks every instance to AppError.prototype. Replace AppError.prototype with new.target.prototype in the base class. new.target is the constructor that new was called with (AuthError here), so every subclass gets its own prototype back without repeating the line.
Exercise
Your error classes include the setPrototypeOf fix, but err instanceof Error still returns false for an error thrown by code running in a Node.js vm context. Does the fix help, and what should the handler check instead?
Show answer
No. That error was built from the vm context's own Error constructor, so its chain leads to a different Error.prototype. The setPrototypeOf fix only repairs ES5 transpilation. Check a stable property such as err.name or a code field, which compares data instead of the identity of the constructor.