How to use the Array.isArray function in JavaScript to check if a value is an array

In JavaScript, you can use the Array.isArray() function to check if a value is an array. This function returns a Boolean value indicating whether the provided value is an array or not.

Here is an example of how you might use the Array.isArray() function:

let myArray = [1, 2, 3];
let myValue = "not an array";

console.log(Array.isArray(myArray));  // outputs "true"
console.log(Array.isArray(myValue));  // outputs "false"

You can also use it with a variable to check if it's an array or not, like this:

let myArray = [1, 2, 3];
let myValue = "not an array";
let anotherValue = [1,2]

if(Array.isArray(myArray)){
  console.log("MyArray is an array")
}
else{
  console.log("MyArray is not an array")
}

if(Array.isArray(myValue)){
  console.log("MyValue is an array")
}
else{
  console.log("MyValue is not an array")
}

if(Array.isArray(anotherValue)){
  console.log("AnotherValue is an array")
}
else{
  console.log("AnotherValue is not an array")
}

It will output:

MyArray is an array
MyValue is not an array
AnotherValue is an array

It's important to note that Array.isArray() returns true only if the value passed to it is an array created using the Array constructor or the array literal notation ([]). If you create an array-like object using other means (such as using the Object.create() method), the Array.isArray() function will return false for that object, even though it may have all of the properties and methods of an array.

Additionally, Array.isArray() is a static method of the Array object and it's present in all modern browser and also in node.js.

Additional resources
  • Frontend web development courses

    Beginner-friendly courses focusing on HTML, CSS, and JavaScript.

    View Courses
  • Frontend web development projects

    Beginner-friendly projects focusing on HTML, CSS, and JavaScript.

    View Projects
  • Free website templates

    Collection of free, high-quality website templates for your next project.

    View Templates