How do you check whether a value is an array in JavaScript?
Use Array.isArray(value). typeof returns "object" for arrays, and instanceof Array can fail for arrays created in another frame or realm.
Explain it simply
Arrays are a special kind of object, so typeof cannot tell them apart from a plain object: both say "object". You need a check that knows about arrays specifically.
Options:
Array.isArray(value): the right answer. Built for exactly this job, and works everywhere.value instanceof Array: works in most cases, but fails when the array came from a different window, such as an iframe, because each window has its ownArrayconstructor.Object.prototype.toString.call(value) === "[object Array]": an older trick from before ES5.
Example
const marks = [78, 91, 66];
const student = { name: "Neha", marks: 3 };
const arrayLike = { 0: "a", 1: "b", length: 2 };
console.log(typeof marks); // Output: object
console.log(Array.isArray(marks)); // Output: true
console.log(Array.isArray(student)); // Output: false
console.log(Array.isArray(arrayLike)); // Output: false
console.log(Object.prototype.toString.call(marks)); // Output: [object Array]
console.log(Array.isArray(Array.from(arrayLike))); // Output: trueAn object with a length property is "array-like" but not an array. Array.from turns it into a real one.
What to say in the interview
"I use Array.isArray. typeof gives 'object' for arrays, and instanceof Array breaks across realms like iframes because each has its own Array constructor. Array.isArray checks the internal type, so it's reliable. Before ES5, people used Object.prototype.toString.call(value)."
Common mistakes
- Checking
value.lengthto decide it is an array; strings and array-like objects havelengthtoo.