instanceof
`x instanceof C` is `true` if the object `x` was created by class `C` (or by a class that extends `C`), and `false` otherwise.
instanceof is an operator that sits between a value and a class. Read it as: "is this value an instance of this class?". It returns a boolean.
Under the hood, JavaScript walks the object's prototype chain looking for the class's prototype. That is why an instance of a subclass also counts as an instance of its parent class.
In the course you use it to check the result of new, as in anaCart instanceof Cart, and in a catch to learn which kind of error arrived: error instanceof Error.
It also helps TypeScript: inside if (x instanceof C), the type checker narrows the type of x to C. That narrowing is gone when Node runs the code, but the instanceof check stays, because it is real JavaScript.
It only works with objects made by a class or constructor function. With a primitive string or number it is always false (if the value is any or unknown).
Reach for it when: you hold a value of uncertain type (an error in a `catch`, for example) and need to know whether it is an instance of a certain class before using it.
Examples
Common mistake
const name: any = "Ana"; console.log(name instanceof String);
Why: A primitive string is not an object made with `new String()`, so `instanceof` gives `false`. We use `any` here to bypass the compiler check that prevents this common mistake.
How to write it: For primitives use typeof name === "string".
Common mistake
const value: unknown = 5; console.log(value instanceof "Cart");
Why: The right side of `instanceof` must be a class or constructor function, not a string holding its name.
How to write it: Pass the class itself, without quotes: value instanceof Cart.
