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!
I’m seeing too wrong or the last two
console.log
are the same?– Costamilam
@You’re right, you should be
Kawasaki
, corrected.– Sergio