When and how to use instanceof and typeof operator in Javascript

Asked

Viewed 1,024 times

17

When and how to use operator instanceof and typeof in Javascript?

In a post do Stack EN I see the usability of instanceof. However, in another post Stack EN says that it is not necessary to use any other operator than the typeof. So I’d like to see situational examples of both operators.

3 answers

14


The instanceof and the typeof have in fact ways to use that overlap. But they also have differences that make them distinct and applicable in different cases.

Notice that the typeof gives object for the following cases:

typeof (new Date())  // "object"
typeof [1, 2, 3]     // "object"
typeof {foo: 'bar'}  // "object"

and in the case of the examples above you can have a more specific answer with the instanceof:

(new Date()) instanceof Date // true
[1, 2, 3] instanceof Array   // true
({foo: 'bar'}) instanceof Object // true

Remember however that in Javascript the following is also valid:

(new Date()) instanceof Object // true
[1, 2, 3] instanceof Object    // true

So it’s good to be specific with the instance that compares.

Another use where the instanceof is very useful is to know if an object or class is an instance/inherits from another. Note the example below and the results of console.log():

class Transporte {
  constructor(marca) {
    this.tipo = marca;
  }
}

class Carro extends Transporte {
  constructor(marca) {
    super(marca);
    this.tipo = 'Carro';
  }
}

class Mota extends Transporte {
  constructor(marca) {
    super(marca);
    this.tipo = 'Mota';
  }
}

const VW = new Carro('Volkswagen');
const Kawasaki = new Mota('Kawasaki');

console.log(VW instanceof Carro); // true
console.log(Kawasaki instanceof Mota); // true
console.log(Kawasaki instanceof Carro); // false
console.log(VW instanceof Transporte); // true
console.log(Kawasaki instanceof Transporte); // true

  • I’m seeing too wrong or the last two console.log are the same?

  • @You’re right, you should be Kawasaki, corrected.

5

The typeof and the instanceof are complementary and have different syntaxes.

The typeof checks the primitive type of a value, and always returns one of the following strings:

"undefined"
"boolean"
"number"
"string"
"object"
"function"
"symbol"

Already the instanceof traverses the prototype chain of a given object, and checks whether in that string there is reference to a second object, returning a boolean. This is to check whether one object inherits from another.

As it turns out, they are totally different functions, besides the fact that the typeof apply to any value, and the instanceof objects only. There is some confusion because the typeof never distinguishes the type of object (except in the case of functions and symbols), and for this it is necessary to use the instanceof and/or other techniques. There is also the case of typeof null === "object", which may seem confusing but has explanation.

I take this opportunity to clarify a misunderstanding of your question, when you say:

Put into another post do Stack EN says it is not necessary to use any other operator besides typeof

Actually that’s not what this post says. It just says that to find out if a value is a function, it’s best to use the typeof than the function isFunction of the underscore library.

5

The typeof operator always results in a string with the primitive object type name. For example, if you execute the following command:

var a = typeof 1; 

The variable a will have the string "number" as its value. That is, if you want to execute a code if the variable value be of the primitive type number, you must do:

if (typeof value === "number") {
   // ...
} 

In the above case, the expression typeof value will be resolved to a string with the type of value, which will then be compared with the string "number".

The instanceof results in a boolean indicating whether an object was generated (directly or indirectly) by a constructor function: obj instanceof func.

function Carro(cor, nome) {
   this.cor = cor;
   this.nome = nome;
}

var foo = new Carro("preto", "ka");
var bar = "teste";

foo instanceof Carro; // retorna true
bar instanceof Carro; // retorna false

Therefore, if you want to make an if with instanceof, it should look like this:

if (obj instanceof Carro) {
   //
}

since the expression obj instanceof Car will be solved for a Boolean.

Note that in the example below, the return value of typeof is "Object", i.e., typeof can never be used to test whether an object was created by a certain constructor function, but only to test the primitive type of the object.

var foo = new Carro();
typeof foo; // retorna "object"

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.