How to Check If a Variable is an Array in JavaScript

To check if a Variable is an array in JavaScript, you can use the “array.isArray()” function. The “isArray()” function returns true if an object is an Array; otherwise, it returns false.

Syntax

Array.isArray(obj)

Arguments

It takes an obj as a required parameter. It is an object to be tested.

Return Value

It returns a Boolean value. It returns true if the object is an array. Otherwise, it returns false.

Example

console.log(Array.isArray([11, 21, 19]))

console.log(Array.isArray({ data: 1121 }))

console.log(Array.isArray('dataset'))

console.log(Array.isArray(undefined))

Output

true
false
false
false

You can see that the isArray() function checks whether the value is an array.

The Array.isArray() method is the most reliable and recommended way to check if a variable is an array in JavaScript. It works correctly with arrays created in different JavaScript contexts (e.g., different windows or iframes), which can cause issues with other methods, such as using instanceof of Array.

Leave a Comment