Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use toString() to typecheck args that you can check with typeof?

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
like image 496
ryanve Avatar asked Mar 01 '12 08:03

ryanve


People also ask

How do you check type in JavaScript?

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.

What is typeof for a class in JavaScript?

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.

What is object type JS?

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.


1 Answers

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]

like image 109
ryanve Avatar answered Sep 20 '22 14:09

ryanve