How to Determine if a Value is an Array with JavaScript

  • 2 min read
  • December 6, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

JavaScript’s Array.isArray() method tells us whether or not a given value is an array.

Syntax

The syntax for Array.isArray() is as follows:

Array.isArray(value)

Simply pass the value you wish to check for Array status as a parameter to the method above.

Array.isArray() returns true if the value is an array, and false otherwise.

Array.isArray() basic example

The following is a basic example demonstrating the use of Array.isArray():

const animals = ['lion', 'dragonfly', 'snake', 'wildebeest'];
console.log(Array.isArray(animals));
// Expected output: true

In the example above, const animals points to an array. This variable is passed into the Array.isArray() method as an argument. As the variable animals is an array, the method returns true.

It is possible to pass other arguments to Array.isArray(), instead of just passing variables:

const mix = ['Type', 4, ['A', 'B', 'C'], { name: 'Shelly', age: 69 }];
console.log(Array.isArray(mix[2]));
// Expected output: true

In the above example, The Array.isArray() method is used to verify whether the third item (index = 2) in the mix array is an array.

The third item in the mix array is [‘A’, ‘B’, ‘C’], which is an array. Therefore, the Array.isArray() method returns true for this expression.

 

Related Articles

JavaScript – How to Search Arrays

JavaScript – How to Use the Array length Property

JavaScript – How to Use the Array sort() Method

Related Posts

How to Use parseInt() in JavaScript

How to Use parseInt() in JavaScript

The parseInt function parses a string argument and returns an integer. In its most simple form, the function looks like this: const x = ‘8’; console.log(parseInt(x));

How to Use promises in JavaScript

How to Use promises in JavaScript

JavaScript is a synchronous language, yet sometimes asynchronous behavior is required. For example, you may need to use an asynchronous function while waiting for data to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement