Vai al contenuto principale
← ⚡ JavaScript & the browser·Modulo C5 · Lezione 4
CompitoWrite show(x): Date → ISO string, Error → "ERR: <message>", everything else → String(x). Log show(new Date(0)), show(new TypeError("boom")), show(42), show("hi").

instanceof for Date and custom classes

100 XP8 min
Teoria

What instanceof tests

x instanceof Constructor returns true if x was made with new Constructor() (or a subclass). It's the type guard for class-based values like Date, Error, Map, Set, or your own classes.

const d = new Date();
d instanceof Date;       // true

const err = new TypeError("x");
err instanceof TypeError; // true
err instanceof Error;     // true  (TypeError extends Error)
err instanceof Date;      // false

class User { constructor(name) { this.name = name; } }
new User("Anna") instanceof User; // true

Common pattern: handle Date, Error, or plain text

function show(x) {
  if (x instanceof Date)  return x.toISOString();
  if (x instanceof Error) return "ERR: " + x.message;
  return String(x);
}

Versus typeof

typeof new Date() returns "object". Useless. instanceof Date is the actual answer.

🔒

Iscriviti per iniziare a programmare

La teoria è aperta a tutti. Editor, anteprima e check si sbloccano con una prova gratuita di 7 giorni — carta richiesta, annullabile in qualsiasi momento.

Iscriviti — prova gratuita →

Le prime 10 lezioni di ogni percorso sono gratuite. Nessuna carta richiesta.

← PrecedenteProssima lezione →

Ricevi un consiglio Python o web al giorno — via email

Breve, scritto a mano, niente spam. Disiscriviti in un clic.