Question

How to Check if a Variable Is an Array in JavaScript

javascriptarrayslistvariables

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:

  • true when value is an array
  • false for everything else, including ordinary objects, strings, numbers, null, and undefined
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.

Although variable.constructor === Array can appear to work, it is not the preferred test. The constructor property can be changed, missing, or unreliable for arrays created in another JavaScript realm, such as an iframe.

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.

Take Quiz

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.isArray(tags)) {
  console.log(`There are ${tags.length} tags.`);
} else {
  console.log("Tags must be an array.");
}

An empty array is still an array:

Array.isArray([]); // true

Do not confuse an array with an array-like object. This object has numeric keys and a length property, but it is not an array:

const arrayLike = { 0: "a", 1: "b", length: 2 };

Array.isArray(arrayLike); // false

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:

  1. input is assigned an array containing two strings.
  2. Array.isArray(input) evaluates to true.
  3. The ! operator reverses that result, so !true becomes false.
  4. Because the if condition is false, JavaScript skips the first block.
  5. JavaScript runs the else block.
  6. input.join(", ") combines the values into "email, notifications".

Now change the input:

const input = "email";

Array.isArray(input) is false, so !false is true. The validation message runs, and the code does not try to call .join() on a string.

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.items is 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 allowedOrigins or plugins.
  • 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"]
getProductNames({ products: null }); // []
Take Quiz

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:

  • Throw an error when a non-array indicates a programming mistake.
  • Return a fallback when missing data is expected and harmless.
  • Report a validation error when the value came from a user or external API.

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 === Array); // false
console.log(Array.isArray(values)); // true

Also, accessing .constructor on null or undefined throws an error:

const value = null;

// value.constructor === Array; // TypeError
Array.isArray(value); // false

Checking truthiness instead of the type

An empty array is truthy, but so are ordinary objects and non-empty strings.

if (value) {
  // This does not prove that value is an array.
}

Assuming array-like values are arrays

Some browser and library objects have a length property but are not arrays. Check with Array.isArray() first, then convert if necessary:

const arrayLike = { 0: "a", 1: "b", length: 2 };
const letters = Array.from(arrayLike);

console.log(Array.isArray(letters)); // true

Comparisons

ApproachIdentifies arrays correctly?Notes
Array.isArray(value)YesRecommended built-in method; safely returns false for null and undefined.
value.constructor === ArrayNot alwaysCan fail if constructor is modified and throws for null or undefined.
typeof value === "object"NoArrays and ordinary objects both have type "object".
value instanceof ArrayUsuallyCan fail for arrays created in another realm, such as an iframe.
Object.prototype.toString.call(value) === "[object Array]"YesOlder, verbose alternative; usually unnecessary today.

For modern JavaScript, prefer:

Array.isArray(value)
Take Quiz

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 === Array for validation.
  • An object with length is not necessarily an array.
  • If you need an array from an iterable or array-like value, use Array.from(value) after appropriate validation.

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:

const isStringArray = Array.isArray(value) && value.every(
  (item) => typeof item === "string"
);

What is the difference between an array and an array-like object?

An array-like object may have indexed properties and a length, but it does not have the full array identity or array methods. Array.isArray() returns false for it.

Take Quiz

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

  1. Create a function named createReceipt that accepts one parameter.
  2. Return "No items provided." when the parameter is not an array.
  3. Return "Your cart is empty." when the array has no items.
  4. Return each item on a separate numbered line when the array contains items.
  5. Test the function with a valid array, an empty array, and a non-array value.
Take Quiz

Keep learning

Related questions

View more