JavaScript, typeof
and instanceof
it can be used to determine the type of data, when to choose typeof
? When choosing instanceof
?
typeof
Operators
typeof
Operator returns the following values are
- Primitive data types
typeof 123 // "number"
typeof '123' // "string"
typeof false // "boolean"
- Function Type
function f() {}
typeof f
// "function"
- undefined
typeof undefined
// "undefined"
var x
typeof x
// "undefined
- Object
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object
instanceof
Operators
instanceof
It is to determine whether the instance variable of an object, the return value is true or false.
var o = {};
var a = [];
o instanceof Array // false
a instanceof Array // true
a instanceof Object // true
typeof array [] {} and the target values are returned Object, arrays and objects can not be distinguished, but instanceof
can be distinguished.
For when to use typeof
andinstanceof
- When the variable is possible to use typeof operator when the undefined
alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception
- When used as a variable may be null when the
instanceof
operator
var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar instanceof Object); // alerts "false"