;

How to Check if an Object is an Array or Not in Javascript


Tutorialsrack 12/03/2020 Jquery Javascript

In this article, we will learn how to check if an object is an array or not in javascript.

There are various ways to check if an object is an array or not in javascript.

Example 1: In this example, we will use the isArray() method to check if an object is an array or not in javascript. This method returns true if an object is an array, otherwise, it returns false. This method works well in all modern browsers.

Example 1
// use isArray() method to check if variable is an array or not
let arr=[1,4,3,2,5,6,7,45];
let arr1=[{id:1,name:'tutorialsrack'},{id:2,name:'tutorialsrack.com'}];
let arr2={id:1,name:'tutorialsrack'};
let value=5;
console.log(Array.isArray(arr)); // it returns true
console.log(Array.isArray(arr1)); // it returns true
console.log(Array.isArray(arr2)); // it returns false
console.log(Array.isArray(value)); // it returns false

Example 2: In this example, we will use the Object.prototype.call() method to check if an object is an array or not in javascript. This method returns true if an object is an array, otherwise, it returns false.

Example 2
//To check if an variable or object is an array or not in javascript
const data = [1,2,3,4,5];
const isArray = Object.prototype.toString.call(data) === '[object Array]';
console.log(isArray); // it returns true
 
 
const data = {id: 1, name: 'tutorialsrack'};
const isArray = Object.prototype.toString.call(data) === '[object Array]';
console.log(isArray); //it returns false

Example 3: In this example, we will use an instanceof Operator to check if an object is an array or not in javascript. This method returns true if an object is an array, otherwise, it returns false.

Example 3
//To check if an variable or object is an array or not in javascript
const data = [1,2,3,4,5];
const isArray = data instanceof Array;
console.log(isArray); //it returns true
 
const data = {id: 1, name: 'tutorialsrack'};
const isArray = data instanceof Array;
console.log(isArray); //it returns false

I hope this article will help you to understand how to check if an object is an array or not in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags