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 Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand 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