I understand why you need to use Object.prototype.toString()
or String()
for typechecking arrays, but isn't typeof sufficient for typechecking functions and strings? For example the polyfill on MDN for Array.isArray uses:
Object.prototype.toString.call(arg) == '[object Array]';
It's pretty clear in the case of arrays because you can't use typeof
to check for arrays. Valentine uses instanceof for this:
ar instanceof Array
But for strings/functions/booleans/numbers, why not use typeof
?
jQuery and Underscore both use something like this to check for functions:
Object.prototype.toString.call(obj) == '[object Function]';
Isn't that equivalent to doing this?
typeof obj === 'function'
or even this?
obj instanceof Function
JavaScript type checking is not as strict as other programming languages. Use the typeof operator for detecting types. There are two variants of the typeof operator syntax: typeof and typeof(expression) . The result of a typeof operator may be misleading at times.
Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.
An object type is simply a collection of properties in the form of name and value pairs. Notice from the list that null and undefined are primitive JavaScript data types, each being a data type containing just one value.
Ok I think I figured out why you see the toString
usage. Consider this:
var toString = Object.prototype.toString;
var strLit = 'example';
var strStr = String('example');
var strObj = new String('example');
console.log(typeof strLit); // string
console.log(typeof strStr); // string
console.log(typeof strObj); // object
console.log(strLit instanceof String); // false
console.log(strStr instanceof String); // false
console.log(strObj instanceof String); // true
console.log(toString.call(strLit)); // [object String]
console.log(toString.call(strStr)); // [object String]
console.log(toString.call(strObj)); // [object String]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With