Question
How can I determine whether a variable contains an array in JavaScript? For example, is this approach reliable?
if (variable.constructor === Array) {
// variable is an array
}
Short Answer
You will learn the recommended way to test for arrays in JavaScript: Array.isArray(value). You will also see why checking constructor is fragile, how to safely handle any value, and where array checks are useful in real code.
Concept
JavaScript values have different types and structures. An array is a special kind of object designed to hold an ordered collection of values.
Use Array.isArray(value) to check whether a value is an array:
Array.isArray(value)
It returns:
truewhenvalueis an arrayfalsefor everything else, including ordinary objects, strings, numbers,null, andundefined
Array.isArray(["red", "blue"]); // true
Array.isArray({ 0: "red", length: 1 }); // false
Array.isArray("red"); // false
This matters because methods such as .map(), .filter(), and .push() are commonly used with arrays. Checking first lets your code validate input and avoid errors such as value.map is not a function.
Mental Model
Think of Array.isArray() as an official scanner at a building entrance. You hand it any value, and it answers one precise question: “Is this an array?”
Checking value.constructor === Array is like looking at a label someone attached to a box. The label may be missing or replaced. Array.isArray() checks the value's actual array identity instead of trusting a changeable property.
Syntax and Examples
The standard syntax is:
Array.isArray(value)
value can be any JavaScript value.
const colors = ["red", "green", "blue"];
const user = { name: "Ada" };
const message = "Hello";
console.log(Array.isArray(colors)); // true
console.log(Array.isArray(user)); // false
console.log(Array.isArray(message)); // false
Use the result in an if statement:
const tags = ["javascript", "arrays"];
if (Array.(tags)) {
.();
} {
.();
}
Step by Step Execution
Consider this input-validation example:
const input = ["email", "notifications"];
if (!Array.isArray(input)) {
console.log("Input must be an array.");
} else {
console.log(input.join(", "));
}
Step by step:
inputis assigned an array containing two strings.Array.isArray(input)evaluates totrue.- The
!operator reverses that result, so!truebecomesfalse. - Because the
ifcondition isfalse, JavaScript skips the first block. - JavaScript runs the
elseblock. input.join(", ")combines the values into"email, notifications".
Real World Use Cases
Array checks are useful whenever code accepts data from outside its immediate control.
- API responses: Verify that a response field such as
response.itemsis an array before rendering a list. - Function arguments: Ensure a utility function received a list of IDs, tags, or files.
- Form data: Confirm a multi-select field contains an array before saving it.
- Configuration: Validate a configuration option such as
allowedOriginsorplugins. - Data processing: Skip, reject, or normalize unexpected values before using
.map()or.filter().
Example: safely process a list returned by an API.
function getProductNames(data) {
if (!Array.isArray(data.products)) {
return [];
}
return data.products.map((product) => product.name);
}
getProductNames({ products: [{ name: "Keyboard" }] }); // ["Keyboard"]
({ : });
Real Codebase Usage
In real projects, developers usually check arrays at boundaries: where API data, user input, configuration, or third-party library values enter the application.
A common pattern is a guard clause. It handles invalid input immediately and keeps the main logic less indented:
function calculateTotal(prices) {
if (!Array.isArray(prices)) {
throw new TypeError("prices must be an array");
}
return prices.reduce((total, price) => total + price, 0);
}
Another pattern is to use a fallback when an absent or invalid value should behave like an empty list:
function renderTasks(tasks) {
const safeTasks = Array.isArray(tasks) ? tasks : [];
return safeTasks.map((task) => `- ${task}`).join("\n");
}
Choose the behavior based on the contract of your code:
Common Mistakes
Using typeof
Arrays are objects in JavaScript, so typeof cannot distinguish them from ordinary objects.
const values = [1, 2, 3];
console.log(typeof values); // "object"
Avoid this:
if (typeof values === "array") {
// This never runs.
}
Use Array.isArray(values) instead.
Using constructor === Array
This may work in simple cases, but constructor is a property that can be changed.
const values = [1, 2, 3];
values.constructor = Object;
console.log(values.constructor === );
.(.(values));
Comparisons
| Approach | Identifies arrays correctly? | Notes |
|---|---|---|
Array.isArray(value) | Yes | Recommended built-in method; safely returns false for null and undefined. |
value.constructor === Array | Not always | Can fail if constructor is modified and throws for null or undefined. |
typeof value === "object" | No | Arrays and ordinary objects both have type "object". |
value instanceof Array | Usually | Can fail for arrays created in another realm, such as an iframe. |
Cheat Sheet
// Recommended array test
Array.isArray(value)
Array.isArray([]); // true
Array.isArray([1, 2]); // true
Array.isArray({}); // false
Array.isArray("text"); // false
Array.isArray(null); // false
Array.isArray(undefined); // false
Rules:
- Use
Array.isArray()before calling array methods on uncertain input. - An empty array (
[]) is still an array. typeof []is"object", not"array".- Avoid
value.constructor === Arrayfor validation. - An object with
lengthis not necessarily an array.
FAQ
What is the best way to check whether a variable is an array in JavaScript?
Use Array.isArray(variable). It returns true only for arrays.
Does typeof work for checking arrays?
No. typeof [] returns "object", which is also returned for ordinary objects.
Is variable.constructor === Array safe?
It is not the recommended approach. The constructor property can be changed, and reading it throws if the value is null or undefined.
Does Array.isArray(null) throw an error?
No. It safely returns false.
Is an empty array considered an array?
Yes. Array.isArray([]) returns true.
How do I check for an array of strings?
First check that the value is an array, then check its elements:
isStringArray = .(value) && value.(
item ===
);
Mini Project
Description
Build a small function that turns a list of shopping items into a readable receipt. The function must validate its input before using array methods, just as production code validates data received from forms or APIs.
Goal
Create a createReceipt function that accepts an array of item names and returns a numbered receipt, or a helpful message for invalid input.
Requirements
- Create a function named
createReceiptthat accepts one parameter. - Return
"No items provided."when the parameter is not an array. - Return
"Your cart is empty."when the array has no items. - Return each item on a separate numbered line when the array contains items.
- Test the function with a valid array, an empty array, and a non-array value.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.