Skip to content

JavaScript is_array

Here is a JavaScript is_array() function. It returns true if the given input is an array, similar to the PHP is_array() function. Works in all browsers.

[JavaScript is_array] Options

Credits

By Andrew Peace.

JavaScript is_array function

Here's my version of PHP's is_array() function, made for JavaScript. Feel free to copy-and-paste it:

The Function

<script type="text/javascript">
  function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
  }
</script>

Using is_array

Using the JavaScript is_array() is the same as in PHP. Just pass it a variable, and it will return true if the variable is an array:

<script type="text/javascript">
  //is names an array?
  if(is_array(names)){
    alert("names is an array!");
  } else {
    alert("names is not an array...");
  }
</script>

Code Explanation

Let's break down the two pieces of this function.

The typeof() function accepts any input and will return that input's type. So, if it says that the type of our function input is 'object', that means our input is an object. An array is a type of object in JavaScript.

Here is a list of some common JavaScript variable types:

Next, we just make sure that the input is the correct type of object. We can check if it is an instance of the Array object by using instanceof.