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.


Recommended Posts

View All

What is the let keyword in JavaScript?


Learn all about the let keyword in JavaScript and how it differs from var. Explore its scope, hoisting, and best practices for usage.

What is the Temporal Dead Zone in JavaScript?


The time frame in which access to the let and const declarations is prohibited is known as the Temporal Dead Zone.

JavaScript Template Literals Explained


JavaScript template literals are one of JavaScript's most powerful capabilities. They enable us to generate dynamic strings without the need for conca...

10 JavaScript Tricks Every Developer Should Know


I'll show you several JavaScript tricks for optimizing your JavaScript code. Use these JavaScript tricks to optimize your JavaScript code.

JavaScript Immediately-invoked Function Expressions (IIFE)


Learn about Immediately-invoked Function Expressions (IIFE) in JavaScript. Understand their benefits and how to use them effectively. Start coding now