How do we check if an object is an array in Javascript?

JavascriptFront End TechnologyObject Oriented Programming

There are multiple ways to check if an object is an array in JavaScript. Let us look at some of these −

Using Array.isArray()

All modern browsers support this method.

Example

console.log(Array.isArray(undefined))
console.log(Array.isArray(null))
console.log(Array.isArray(""))
console.log(Array.isArray({}))
console.log(Array.isArray([]))
console.log(Array.isArray([1, "hello"]))
console.log(Array.isArray(new Array()))

Output

false
false
false
false
true
true
true

constructor check

You can use arr.constructor === Array to determine is an object is array. This doesnt work for all objects though.

Example

// This will fail: console.log(undefined.constructor === Array)
// This will fail: console.log(null.constructor === Array)
console.log("".constructor === Array)
console.log({}.constructor === Array)
console.log([].constructor === Array)
console.log([1, "hello"].constructor === Array)
console.log(new Array().constructor === Array)

Output

false
false
true
true
true
raja
Published on 16-Sep-2019 08:02:29
Advertisements