How to check if a JavaScript object is an array?

This video show you how to check if a JavaScript object is an array.

Code

let names = ["samy", "trisa", "kim"];
Array.isArray(names)
Array.isArray("a")
Array.isArray(undefined)
Array.isArray(null)
Array.isArray({"a": 123})
typeof names === "object"

Full Transcript

Our goal today is to find out if a given object is an array. Let's say we have a variable called names whose value is an array containing strings. Let those strings be sammy, trisa and kim. Now arrays in JavaScript have a method called isArray(), which determines if the value pass to it as an argument is an array. So to check if names is an array, we call array.isArray() and pass names as argument. As you can see, it returns true. If we want to check for a string, a it returns false. For undefined values, it returns false and same for null values. Now, if you pass an object containing the key value pair, it does return false. Often this confusion stems from the fact that arrays are objects, so to be able to check if a given object is an array, you should always use array.isArray() method.