It internally works by testing if the right operand appears anywhere in the prototype chain of the left.
function Person() { this.name = 'KK';}var person = new Person();console.log(person instanceof Person); // trueconsole.log(person instanceof Object); // trueconsole.log([1,2,3] instanceof Array); // trueconsole.log('abc' instanceof String); // false since 'abc' is primitive and not object of Stringconsole.log(new String('abc') instanceof String); // true
Checking Array can also be done using Array.isArray() but it fails across iframe (rare scenario)
Primitive datatypes can have methods which can be called
To achieve this JS creates a wrapper function before calling the method
let str = "Hello";alert( str.toUpperCase() ); // HELLO
For each primitive we have wrapper class like String for string. So a wrapper object is created for str and then toUpperCase() method is called. After JS is done calling the method the wrapper class object is destroyed
Number() vs new Number()
Always avoid creating a primitive using wrapper class constructor.
var x = new Number() is highly discouraged and will cause x to be an object instead of primitive
Corresponding function without invoking constructor is fine since it helps in converting primitive
var x = Number('123') is perfectly fine and x will be number primitive here