JavaScript isArray(): Check if an Object is an Array or Not

The JavaScript isArray() method is used to check whether a specified object is an array or not. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const countries = ["Luxembourg", "USA", "Australia", "UK", "USA", "Canada"];
      let x = Array.isArray(countries);
      
      if(x)
         document.getElementById("xyz").innerHTML = "'countries' is an Array.";
      else
         document.getElementById("xyz").innerHTML = "'countries' is not an Array.";
   </script>
   
</body>
</html>
Output

In the above example, the first line

<!DOCTYPE html>

is the document type declaration for an HTML file.

The code within the <html> and <body> tags is the HTML markup for creating a web page. The <p> tag creates a paragraph element with an id attribute of "xyz".

The JavaScript code starts with the <script> tag and ends with the </script> tag.

The const keyword is used to declare a constant variable named countries. It is an array of strings containing the names of several countries.

The Array.isArray() method is used to determine whether the countries variable is an array. This method's return value is saved in a variable called x.

The code then uses an if-else statement to check the value of x. If it is true, it means that countries is an array, so the text "'countries' is an Array." is set as the inner HTML of the paragraph element with the id "xyz" using the document.getElementById() method. Otherwise, the text "'countries' is not an Array." is set as the inner HTML of the same paragraph element.

JavaScript isArray() syntax

The syntax of the isArray() method in JavaScript is:

Array.isArray(object)

Note: The Array before isArray() is necessary because of the static property.

The isArray() method returns true if the specified object is an array; otherwise, it returns false. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>

   <script>
      let myVar = "codescracker.com";
      document.getElementById("abc").innerHTML = Array.isArray(myVar);
   </script>
   
</body>
</html>
Output

This example checks whether a variable myVar is an array or not using the Array.isArray() method in JavaScript. The Array.isArray() method returns true if the passed-in argument is an array, and false if it is not an array.

In this code, the myVar variable is assigned a string value "codescracker.com". The code then uses the document.getElementById() method to select the paragraph element with the id attribute "abc".

The innerHTML property of the paragraph element is then set to the result of Array.isArray(myVar), which will be false since myVar is not an array.

Therefore, when this code is executed, the text "false" will be displayed inside the paragraph element with the id attribute "abc".

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!