Skip to content

Check if the 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

Another example

const myObject = [1, 2, 3];

if (Array.isArray(myObject)) {
  console.log('myObject is an array');
} else {
  console.log('myObject is not an array');
}

In this example, myObject is an array, so the output will be “myObject is an array”. If you were to use a non-array object, the output would indicate that it’s not an array.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading