true
typeof returns object
for all values except primitve type. (null
is one exception.)
typeof([1,2,3]); // 'object'
typeof({}); // 'object'
typeof(1); // 'number'
typeof(null); // 'object'
It is ueless to distinguish between different kinds of objects.
It checks whether object is instance of certain type.
function Animal(){};
var a = new Animal();
console.log(a instanceof Animal); // true
console.log([1,2,3] instanceof Array); // true
We can use constructor
method to check the type.
console.log(a.constructor == Animal); // true
console.log([1,2,3].constructor = Array); // true
Not walks up the prototype chain.
Error with primitve values.
console.log(3 instanceof Number); // false
console.log(true instanceof Boolean); // false
For alternative, we can use constructor
method for number, string, boolean type values. This works because, Javascript autoboxes given primitive type values with object wrapper. Precisely, it makes primitive value to object type, so this is why it works.
console.log((3).constructor == Number); // true
console.log('abc'.constructor == String); // true
undefined
represents the value that doesn't exists in compiler. Following situations returns undefined
. undefined
is not a literal , it is a property of global object.
unassgined variable
undeclared object property
default return value of function which doesn't returns
value using void operator
null
however, represents the intentional absence of vaule. There is a bug with null
using typeof method.
console.log(typeof null); // object
strict equality is no slower than loose equality because they both check the operand types.
strict equality is faster than loose equality when types of operands differ.
of course, loose equality produces unexpected results.