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
A common pattern is to normalize input:
const items = Array.isArray(value) ? value : [value];
Now items is always an array, so you can safely loop over it.
This idea is very useful in real programming because many APIs, utility functions, and data-processing helpers accept flexible input but convert it into one reliable internal format before doing any work.
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.log(normalizeToArray("apple"));
// ["apple"]
console.log(normalizeToArray(["apple", "banana"]));
// ["apple", "banana"]
Looping safely after normalization
function printItems(value) {
const items = Array.isArray(value) ? value : [value];
for (const item of items) {
console.log(item);
}
}
printItems("apple");
// apple
printItems(["apple", "banana"]);
// apple
// banana
Restricting input to strings or arrays of strings
If you want stricter input handling, add validation:
function handleStrings(value) {
const items = Array.isArray(value) ? value : [value];
for (const item of items) {
if (typeof item !== "string") {
throw new Error("Expected a string or an array of strings");
}
}
return items;
}
This is useful when you want to prevent invalid input such as numbers or objects.
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"orange".console.log(item)printsorange.
Now compare it with this call:
handleInput(["orange", "grape"]);
What changes?
valueis already an array.Array.isArray(value)returnstrue.- The ternary operator keeps the original array unchanged.
- The loop runs twice.
- It prints
orange, thengrape.
This shows the benefit of normalization: after one check, the rest of the function can treat the input as an array every time.
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", "./b.json"]);
Using Array.isArray() helps support both formats safely.
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
In production code, a function may receive null, undefined, numbers, or objects. Validation prevents hidden bugs.
function toStringArray(input) {
if (input == null) {
return [];
}
const items = Array.isArray(input) ? input : [input];
return items.filter(item => typeof item === "string");
}
Combining with map and filter
Once input is normalized, array methods become easy to use:
const result = (Array.isArray(input) ? input : [input])
.filter(item => typeof item === "string")
.map(item => item.toLowerCase());
This style is common in utility libraries and application services.
Error handling
If the function only supports arrays and strings, be explicit:
function normalizeNames(input) {
if (typeof input !== "string" && !Array.isArray(input)) {
throw new TypeError("Input must be a string or an array of strings");
}
return Array.isArray(input) ? input : [input];
}
This makes bugs easier to debug.
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);
}
}
Why it fails:
- plain objects are not arrays
- many objects cannot be looped with
for...of
Forgetting about null
Broken code:
if (typeof value === "object") {
console.log("Object detected");
}
Why it is confusing:
typeof nullis also"object"
Safer approach:
if (Array.isArray(value)) {
// array logic
}
Wrapping an array again by mistake
Broken code:
const items = [value];
If value is already an array like ["a", "b"], this becomes:
[["a", "b"]]
That is usually not what you want.
Correct version:
const items = Array.isArray(value) ? value : [value];
Not validating element types
Broken code:
function printUpperCase(value) {
const items = Array.isArray(value) ? value : [value];
return items.map(item => item.toUpperCase());
}
This breaks if item is not a string.
Safer version:
function printUpperCase(value) {
const items = Array.isArray(value) ? value : [value];
return items.map(item => {
if (typeof item !== "string") {
throw new Error("All items must be strings");
}
return item.toUpperCase();
});
}
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 |
Array.isArray() vs instanceof Array
Array.isArray(value);
value instanceof Array;
Array.isArray() is preferred because it directly expresses your intent: checking whether something is an array.
Array vs string for looping
| Type | Can store multiple items? | Good for for...of? | Best use |
|---|---|---|---|
| String | Not as separate list items | Yes, but iterates characters | Text data |
| Array | Yes | Yes | Collections of values |
A string like "cat" can be looped over, but it produces "c", "a", and "t", not one whole item. That is why converting a single string into ["cat"] is important when your function expects a list of strings.
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
- Use
Array.isArray()to detect arrays - Do not use
typeof value === "array" typeof []is"object"typeof nullis also"object"- Normalize flexible input before looping
- Validate array contents if your function expects specific types
Common one-liner
const items = Array.isArray(input) ? input : [input];
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 "c", "a", "t".
How do I accept either a string or an array of strings in a function?
Normalize the input first:
function toArray(value) {
return Array.isArray(value) ? value : [value];
}
Then validate items if needed.
What if the value is null or undefined?
Decide on the behavior you want. Some functions throw an error, while others return an empty array:
if (value == null) return [];
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
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.