1if ( !(obj instanceof Array) ) {
2 console.log('obj is not an Array')
3}
1An instanceof in Java is a comparison operator which, given an object instance,
2checks whether that instance is of a specified type (class/sub-class/interface)
3or not. Just like other comparison operators, it returns true or false.
4
5Comparing any object instance with a null type through instanceof operator
6returns a false.
7
8Instanceof operator is used to test the object is of which type.
9
10Syntax : <reference expression> instanceof <destination type>
11Instanceof returns true if reference expression is subtype of destination type.
12Instanceof returns false if reference expression is null.
1var color = "red";
2var color2 = {};
3color instanceof String // will return true
4color2 instanceof Object // will return true
5
1The instanceof operator tests to see if the prototype property of a constructor
2appears anywhere in the prototype chain of an object. The return value is a
3boolean value.
4For example :-
5
6function Car(make, model, year) {
7 this.make = make;
8 this.model = model;
9 this.year = year;
10}
11const auto = new Car('Honda', 'Accord', 1998);
12
13console.log(auto instanceof Car);
14// expected output: true
15
16console.log(auto instanceof Object);
17// expected output: true
18
1function Phone(serial, price, color){
2 this.serial = serial;
3 this.price = price;
4 this.color = color;
5}
6
7let phone1 = new Phone('abc1', 200, 'red');
8let phone2 = new Phone('abc2', 400, 'green');
9
10//instanceof
11console.log(phone1 instanceof Phone) // true
12
13//constructor
14console.log(phone1.constructor === Phone) //true