📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Example 1 - Simple instanceof Operator Example
class Person{
firstName;
lastName;
}
class Employee extends Person{
}
class Manager extends Person{
}
function testInstanceOfOperator(){
const employee = new Employee();
const manager = new Manager();
// should print true
console.log(employee instanceof Employee);
console.log(employee instanceof Person);
console.log(manager instanceof Manager);
console.log(manager instanceof Person);
// should print false
console.log(manager instanceof Employee);
console.log(employee instanceof Manager);
}
testInstanceOfOperator();
true
true
true
true
false
false
Example - Demonstrating that String and Date are of type Object and exceptional cases
var simpleStr = 'This is a simple string';
var myString = new String();
var newStr = new String('String created with constructor');
var myDate = new Date();
var myObj = {};
var myNonObj = Object.create(null);
simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
myString instanceof String; // returns true
newStr instanceof String; // returns true
myString instanceof Object; // returns true
myObj instanceof Object; // returns true, despite an undefined prototype
({}) instanceof Object; // returns true, same case as above
myNonObj instanceof Object; // returns false, a way to create an object that is not an instance of Object
myString instanceof Date; // returns false
myDate instanceof Date; // returns true
myDate instanceof Object; // returns true
myDate instanceof String; // returns false
Example 3 - Demonstrating that mycar is of type Car and type Object
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car('Honda', 'Accord', 1998);
var a = mycar instanceof Car; // returns true
var b = mycar instanceof Object; // returns true
Comments
Post a Comment
Leave Comment