Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type typeof(array) in JavaScript is object not array? [duplicate]

Either we check type of array or object it always print object in JavaScript. Why so?

let arr=[1,3,4];
let obj={1:"44",num:44};

console.log(typeof(arr)) //object
console.log(typeof(obj)) //object

Is there any way to see typeof(array) as array?

like image 682
SOURABH GUPTA Avatar asked Jan 30 '26 10:01

SOURABH GUPTA


2 Answers

Try using the instanceof operator

const arr = [];
console.log(arr instanceof Array); // true

const obj = {};
console.log(obj instanceof Array); // false
like image 86
lostsource Avatar answered Feb 01 '26 03:02

lostsource


Because an array is technically a type of object - just with certain abilities and behaviors, for instance additional methods like Array.prototype.push() and Array.prototype.unshift(). Arrays are regular objects where there is a particular relationship between integer-key-ed properties and the length property.

To determine whether you have an array specifically, you can use Array.isArray().

like image 24
Muirik Avatar answered Feb 01 '26 02:02

Muirik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!