The function toString method?from Object.prototype is the best approach to determine whether an object is an instance of a given class or not.
var arrayList = [1 , 2, 3];
When we utilize method overloading in JavaScript, type checking an object is one of the greatest applications. Let's assume we have a method named greet that can accept both a single string and a list of strings in order to better comprehend this. We need to know what sort of parameter is being supplied in order to make our greet method functional in both scenarios: is it a single value or a list of values?
function greet(param) { if() { // here have to check whether param is array or not } else { } }
However, given the method above, it might not be essential to determine the type of the array. Instead, we can determine whether the array has a single value string and then place the array logic code in the else block.
function greet(param) { if(typeof param === 'string') { } else { // If param is of type array then this block of code would execute } }
Right now, using the two previous implementations is fine, but when a parameter can be an object type, an array, or a single value, things get tricky.
Resuming our discussion of determining an object's type, we can do so by using Object.prototype.toString.
if(Object.prototype.toString.call(arrayList) === '[object Array]') { console.log('Array!'); }
You can use the jQuery isArray method if you're already using jQuery:
if($.isArray(arrayList)) { console.log('Array'); } else { console.log('Not an array'); }
FYI To determine if an object is an array or not, jQuery internally uses the Object.prototype.toString.call method.
You can also use a modern browser to:
Array.isArray(arrayList);
Array.is Chrome 5, Firefox 4.0, Internet Explorer 9, Opera 10.5 and Safari 5 all support array.