javascript – Why does instanceof of a number literal return false?

Question:

That is, as you can see in the example below, the prototype of all the given objects is of type Number , but if a:

const obj = 9;

obj instanceof Number // false

without having gone through a

new Number(obj) instanceof Number // true

It will always return false , examples:

var is = Function.prototype.call.bind(Object.prototype.toString);
var log = console.log.bind(console);
const num = 9;

log(typeof(9));                         // number
log(is(9));                             // [object Number]
log(9 instanceof Number);               // false
log('');

log(typeof(num));                       // number
log(is(num));                           // [object Number]
log(num instanceof Number);             // false
log('');

log(typeof(new Number(9)));             // object
log(is(new Number(9)));                 // [object Number]
log(new Number(9) instanceof Number);   // true
log('');

log(typeof(new Number(num)));           // object
log(is(new Number(num)));               // [object Number]
log(new Number(num) instanceof Number); // true

Why does this happen?

Answer:

The problem is that not every value in javascript is an object, they can also be primitives (commonly called literals), and, according to the specification , instanceof only checks that a value is an instance (object) of a certain type: in other words, that has been initialized by new Tipo .

That is why it is common to do this type of evaluation in javascript:

function isString(s) {
  return typeof(s) === 'string' || s instanceof String;
}

Because a string can be a primitive value or an instance of the String class.

Scroll to Top