TL;DR
To check if a variable is an array, you use the Array.isArray()
method or the instanceof
operator:
let colors = ['red','green','blue'];
// #1: use Array.isArray
let isArray = Array.isArray(colors);
console.log(isArray); // true;
// #2: use instanceof operator
isArray = colors instanceof Array;
console.log(isArray); // true;
Code language: JavaScript (javascript)
1) Using Array.isArray(variableName) method to check if a variable is an array
The Array.isArray(variableName)
returns true
if the variableName
is an array. Otherwise, it returns false
.
The Array.isArray()
method is a recommended way to check if a variable is an array because it has good browser support.
The following shows some examples of using the Array.isArray()
method:
const ratings = [1, 2, 3, 4, 5];
const vote = { user: 'John Doe', rating: 5 };
const str = "It isn't an array";
console.log(Array.isArray(ratings)); // true
console.log(Array.isArray(vote)); // false
console.log(Array.isArray(str)); // false
Code language: JavaScript (javascript)
2) Using the instanceof operator to check if a variable is an array
Since all arrays are instances of the Array
type, you can use the instanceof
to check if a variable is an array like this:
variableName instanceof Array
Code language: JavaScript (javascript)
The expression returns true
if the variableName
is an array. For example:
const ratings = [1, 2, 3, 4, 5];
const vote = { user: 'John Doe', rating: 5 };
const str = "It isn't an array";
console.log(ratings instanceof Array); // true
console.log(vote instanceof Array); // false
console.log(str instanceof Array); // false
Code language: JavaScript (javascript)
Summary
- The
Array.isArray(variableName)
returnstrue
if thevariableName
is is an array. - The
variableName instanceof Array
returnstrue
if thevariableName
is an array.
Was this tutorial helpful ?