Question
I am writing a JavaScript function that should accept either:
- a single string, or
- an array of strings
If the input is a single string, I want to convert it into an array containing just that one item so I can loop over it safely.
How can I check whether a variable is an array in JavaScript?
function handleInput(value) {
// How do I detect whether `value` is an array?
}
Short Answer
By the end of this page, you will understand how to detect arrays in JavaScript using Array.isArray(), why it is the safest standard approach, and how to normalize input so your function can handle either a single string or an array of strings consistently.
Concept
In JavaScript, arrays are a special type of object used to store ordered collections of values.
A common beginner question is: how do I tell whether a value is actually an array?
This matters because many functions are easier to write if they always work with one consistent data shape. For example, if a function accepts either:
"apple"- or
["apple", "banana"]
then you often want to convert both cases into a single format, such as an array.
The standard and recommended way to check for an array in JavaScript is:
Array.isArray(value)
It returns:
trueifvalueis an arrayfalseotherwise
This is better than older techniques like typeof because:
typeof []returns"object", not"array"- arrays are objects, so
typeofcannot distinguish them properly Array.isArray()is built specifically for this exact check
Mental Model
Think of a function like a worker receiving packages.
Sometimes the worker receives:
- one item in a small envelope
- many items in a box
The worker wants to process everything the same way, so if a single item arrives, they put it into a box first.
In JavaScript:
- a single string is the one item
- an array is the box
Array.isArray()is the label checker that tells you whether the input is already in a box
Once everything is in a box, the rest of the code becomes simpler.
Syntax and Examples
The core syntax is:
Array.isArray(value)
Basic examples
console.log(Array.isArray(["a", "b"])); // true
console.log(Array.isArray("a")); // false
console.log(Array.isArray({})); // false
console.log(Array.isArray(123)); // false
Converting a single string into an array
function normalizeToArray(value) {
return Array.isArray(value) ? value : [value];
}
console.(());
.(([, ]));
Step by Step Execution
Consider this code:
function handleInput(value) {
const items = Array.isArray(value) ? value : [value];
for (const item of items) {
console.log(item);
}
}
handleInput("orange");
Step-by-step
handleInput("orange")is called.- Inside the function,
valueis the string"orange". Array.isArray(value)is checked.- Since
valueis a string, the result isfalse. - The ternary operator chooses
[value], which becomes["orange"]. itemsnow stores an array with one element.- The
for...ofloop runs over that array. itembecomes .
Real World Use Cases
This pattern appears often in real JavaScript code.
Accepting one item or many
A utility function may accept either:
addTags("news");
addTags(["news", "tech"]);
Internally, it converts both into an array.
API filters
A backend or frontend function may accept one status or multiple statuses:
filterByStatus("active");
filterByStatus(["active", "pending"]);
Form handling
Some form inputs return a single selected value, while others may return multiple values. Normalizing to an array makes processing easier.
Logging and event systems
A function may accept one callback or multiple callbacks. Developers often normalize to an array before iterating.
Configuration options
A config value may allow either:
- one path
- multiple paths
Example:
loadFiles("./data.json");
loadFiles(["./a.json", ]);
Real Codebase Usage
In real projects, developers rarely stop at just checking whether something is an array. They usually combine that check with patterns that make code safer and easier to maintain.
Input normalization
This is the most common pattern:
const items = Array.isArray(input) ? input : [input];
After this line, the rest of the function can assume items is always an array.
Guard clauses
Developers often reject invalid values early:
function processNames(input) {
const items = Array.isArray(input) ? input : [input];
if (!items.every(item => typeof item === "string")) {
throw new Error("Expected a string or an array of strings");
}
return items.map(name => name.trim());
}
This keeps the main logic clean.
Validation before looping
Common Mistakes
Using typeof to check for arrays
Broken code:
if (typeof value === "array") {
console.log("This is an array");
}
Why it fails:
- JavaScript does not return
"array"fromtypeof typeof []returns"object"
Correct version:
if (Array.isArray(value)) {
console.log("This is an array");
}
Treating all objects as arrays
Broken code:
if (typeof value === "object") {
for (const item of value) {
console.log(item);
}
}
Comparisons
| Approach | Works for arrays? | Recommended? | Notes |
|---|---|---|---|
Array.isArray(value) | Yes | Yes | Standard and reliable |
typeof value === "array" | No | No | typeof never returns "array" |
typeof value === "object" | Not specifically | No | Arrays are objects, but so are many other values |
value instanceof Array | Often | Sometimes | Usually works, but Array.isArray() is clearer and safer |
Cheat Sheet
// Best way to check for an array
Array.isArray(value)
Normalize input to an array
const items = Array.isArray(value) ? value : [value];
Validate string or array of strings
function normalizeStrings(value) {
if (typeof value !== "string" && !Array.isArray(value)) {
throw new TypeError("Expected a string or an array of strings");
}
const items = Array.isArray(value) ? value : [value];
if (!items.every(item => typeof item === "string")) {
throw new TypeError("All items must be strings");
}
return items;
}
Important rules
FAQ
How do I check if a variable is an array in JavaScript?
Use:
Array.isArray(value)
This is the standard and recommended approach.
Why does typeof [] return "object"?
Because arrays are a special kind of object in JavaScript. typeof is too broad to distinguish arrays from other objects.
Should I use instanceof Array?
You can, but Array.isArray() is preferred because it is clearer and designed specifically for this purpose.
How do I turn a single string into an array?
Wrap it in square brackets:
const items = ["hello"];
Or conditionally normalize input:
const items = Array.isArray(value) ? value : [value];
Can I loop over a string directly?
Yes, but it loops over characters, not list items. For example, "cat" becomes , , .
Mini Project
Description
Build a small utility function that accepts either a single tag or a list of tags and returns a clean array of tags. This demonstrates array detection, input normalization, and validation—common tasks in real JavaScript applications such as filtering, search, and content management.
Goal
Create a function that safely accepts a string or an array of strings and always returns a validated array of trimmed tag names.
Requirements
- Accept either one string or an array of strings as input.
- Convert a single string into an array containing that string.
- Trim whitespace from each tag.
- Reject non-string values with an error.
- Return the cleaned array.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.