instanceof javascript
if ( !(obj instanceof Array) ) {
console.log('obj is not an Array')
}The instanceof keyword checks whether an object
is an instance of a specific class or an interface.
The instanceof keyword compares the
instance with type. The return value
is either true or false .var color = "red";
var color2 = {};
color instanceof String // will return true
color2 instanceof Object // will return true
//checks if is object, null val returns false
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
var person = {"name":"Boby Snark"};
isObject(person);//truenew Date() instanceof Date; // => trueThe instanceof operator tests to see if the prototype property of a constructor
appears anywhere in the prototype chain of an object. The return value is a
boolean value.
For example :-
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true