If you try to apply the typeof
operator to a JavaScript array, you won’t be able to tell if it’s an array. To check
if a variable is an array in JS, you need to take a different approach.
All JavaScript arrays are objects.
const arr = [1, 2, 3];
const obj = {};
console.log(typeof arr); // object
console.log(typeof obj); // object
You can use the built-in function Array.isArray
to check if a JS variable is an array.
const arr = [1, 2, 3];
const obj = {};
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
An alternative would be to use the instanceof
operator.
const arr = [1, 2, 3];
const obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false