Symbol.hasInstance Customizes The instanceof Check
Override Symbol.hasInstance to accept plain objects by shape, then filter mixed samples through the custom instanceof check.
Code
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static [Symbol.hasInstance](value) {
return value !== null && typeof value === 'object' && typeof value.celsius === 'number';
}
describe() {
return this.celsius.toFixed(1) + 'C';
}
}
const reading = { celsius: 21.5 };
const imperial = { fahrenheit: 70.7 };
console.log('reading:', reading instanceof Temperature);
console.log('imperial:', imperial instanceof Temperature);
console.log('literal:', 21 instanceof Temperature);
console.log('real instance:', new Temperature(19) instanceof Temperature);
console.log('describe:', new Temperature(19).describe());
const samples = [reading, imperial, new Temperature(4)];
const temps = samples.filter((value) => value instanceof Temperature);
console.log('filtered:', temps.length, temps.map((value) => value.celsius ?? 'n/a').join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
reading: true
imperial: false
literal: false
real instance: true
describe: 19.0C
filtered: 2 21.5,4How it works
Symbol.hasInstance Customizes The instanceof Check comes down to the class Temperature.
Module-level bindings hold the data — reading, imperial, samples, temps — with no function scope in between.
The top-level object literal pins celsius as plain values — no derivation, no imports behind them.
Using it
Each run prints the 6 labeled blocks reading:, imperial:, literal:, real instance:, describe:, filtered: in source order.
Key statements
return value !== null && typeof value === 'object' && typeof value.celsius === 'number';
const temps = samples.filter((value) => value instanceof Temperature);
return this.celsius.toFixed(1) + 'C';
Interactive Tools for This Topic
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `reading`, `imperial`, `samples`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.