Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between array and object in javascript? or Array Vs Object

Tags:

javascript

How to recognize array & object in js where typeof doesn’t come in handy?

 var arr = [], ob = {};

As everything in js are objects,

if(typeof arr == typeof ob)  => returns true

I want a operator or ... that will tell me that the variable is an array. I can then use only the arrayfunctions to objects which are array. How is that possible?

like image 440
Angelin Nadar Avatar asked Oct 18 '11 06:10

Angelin Nadar


People also ask

Is array same as object in JavaScript?

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.

Is object object and array JavaScript?

An array is an object. And like any object in JavaScript, the array instance has a constructor function — Array .

What is the difference between object and object in JavaScript?

Javascript is case sensitive "object" is essentially a variable that can hold anything. "Object" is an actual javascript type.


2 Answers

var arr = [], ob = {};

As everything in js are objects, even **Array is an Object but an instance of class Array

if(typeof arr == typeof ob)  => returns true as Both are **Objects

So, how will you to identify objects.

This is where instanceof operator comes in handy, to identify whether its an array you can put a additional check cde:

if(arr instanceof Object && arr instanceof Array) => returns true 
if(ob instanceof Object && ob instanceof Array) => returns false 
like image 118
Angelin Nadar Avatar answered Sep 19 '22 14:09

Angelin Nadar


You could use Array.isArray() method to check if a variable is array or otherwise.

var myArray = [1,2,3,4,5];
console.log(Array.isArray(myArray));

true

like image 40
Harish Avatar answered Sep 20 '22 14:09

Harish