0
0
JavascriptHow-ToBeginner · 3 min read

How to Check if Variable is Array in JavaScript

To check if a variable is an array in JavaScript, use the Array.isArray() method. It returns true if the variable is an array, otherwise false.
📐

Syntax

The syntax to check if a variable is an array uses the Array.isArray() method. You pass the variable as an argument inside the parentheses.

  • Array.isArray(variable): Returns true if variable is an array.
javascript
Array.isArray(variable)
💻

Example

This example shows how to use Array.isArray() to check different variables and print the result.

javascript
const arr = [1, 2, 3];
const str = "hello";
const obj = {a: 1};

console.log(Array.isArray(arr)); // true
console.log(Array.isArray(str)); // false
console.log(Array.isArray(obj)); // false
Output
true false false
⚠️

Common Pitfalls

A common mistake is using typeof to check for arrays, but it returns "object" for arrays, which is not specific enough.

Also, using instanceof Array can fail if arrays come from different frames or windows.

The recommended and reliable way is to always use Array.isArray().

javascript
const arr = [1, 2, 3];

// Wrong way:
console.log(typeof arr === 'array'); // false

// Less reliable way:
console.log(arr instanceof Array); // true (but can fail across frames)

// Correct way:
console.log(Array.isArray(arr)); // true
Output
false true true
📊

Quick Reference

MethodDescriptionReturns
Array.isArray(variable)Checks if variable is an arraytrue or false
typeof variable === 'array'Incorrect: returns 'object' for arraysfalse
variable instanceof ArrayWorks but can fail across framestrue or false

Key Takeaways

Use Array.isArray(variable) to reliably check if a variable is an array.
Avoid using typeof to check for arrays because it returns 'object'.
instanceof Array can fail if arrays come from different frames or windows.
Array.isArray() is the modern and recommended method for this check.