Check if object is Array JavaScript | Example code

  • by

Use the Array isArray() Method to Check if the object is Array in JavaScript. This method checks whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false.

Array.isArray(obj)

Check if the object is Array JavaScript

<!DOCTYPE html>
<html>
<body>

  <script>
    var v1 = {name: "John", age: 18};   
    var v2 = ["red", "green", "blue", "yellow"];
    var v3 = [1, 2, 3, 4, 5];
    var v4 = null;

    console.log(Array.isArray(v1));
    console.log(Array.isArray(v2));
    console.log(Array.isArray(v3));
    console.log(Array.isArray(v4));

  </script>

</body>
</html> 

Output:

Check if object is Array JavaScript

For backward compatibility you can add the following:

// Only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use Underscore.js you can use _.isArray(obj).

If you don’t need to detect arrays created in different frames you can also just use instanceof:

obj instanceof Array

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.