Predict instanceof Output
Predict Output Medium
Question
What does this code print?
Code
class Cat { meow() { return "meow!"; } }
class Dog { bark() { return "woof!"; } }
function speak(animal: Cat | Dog) {
if (animal instanceof Cat) return animal.meow();
return animal.bark();
}
console.log(speak(new Cat()));
console.log(speak(new Dog()));
Hint
instanceof checks the class constructor at runtime.
Explanation
speak(new Cat()) — animal instanceof Cat is true, returns "meow!". speak(new Dog()) — animal instanceof Cat is false, falls through to animal.bark(), returns "woof!". Output: meow! and woof! on separate lines.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.