How to Check if a Variable is an Array in JavaScript?
To check if a variable is an array, we can use the JavaScript isArray() method. It is a very basic method to check a variable is an array or not. Checking if a variable is an array in JavaScript is essential for accurately handling data, as arrays have unique behaviors and methods.
Using JavaScript isArray() Method
The Array.isArray() method checks if a variable is an array. It returns true if the variable is an array and false otherwise. This method is introduced in ECMAScript 5.
Syntax
Array.isArray( variableName )
// Given variables
let n = 10;
console.log("Is Array: ", Array.isArray(n));
let s = "GeeksforGeeks";
console.log("Is Array: ", Array.isArray(s));
let a = [ 10, 20, 30, 40, 50 ];
console.log("Is Array: ", Array.isArray(a));
Output
Is Array: false Is Array: false Is Array: true
Using JavaScript instanceof Operator
The JavaScript instanceof operator is used to test whether the property of a constructor appears anywhere in the chain of an object. This can be used to evaluate if the given variable has a of Array.
Syntax
variable instanceof Array
// Given variables
let n = 10;
console.log("Is Array: ", n instanceof Array);
let s = "GeeksforGeeks";
console.log("Is Array: ", s instanceof Array);
let a = [ 10, 20, 30, 40, 50 ];
console.log("Is Array: ", a instanceof Array);
Output
Is Array: false Is Array: false Is Array: true
Checking Constructor Property of Variable
The approach of checking the constructor property involves verifying if a variable's constructor is Array. If variable.constructor === Array, the variable is an array. This method checks the object's chain but may fail if the array's is altered.
Syntax
variable.constructor === Array
// Given variables
let n = 10;
console.log("Is Array: ", n.constructor === Array);
let s = "GeeksforGeeks";
console.log("Is Array: ", s.constructor === Array);
let a = [ 10, 20, 30, 40, 50 ];
console.log("Is Array: ", a.constructor === Array);
Output
Is Array: false Is Array: false Is Array: true