Reputation: 419
I am trying to understand something in JavaScript.
Lets say I do the following:
let x = [];
x['Monday'] = 'Work';
x['Tuesday'] = 'More Work';
console.log(x) //[Monday: "Work", Tuesday: "More Work"]
console.log(x.Monday) //"Work"
console.log(x.Tuesday) //"More Work"
Can someone help explain why the array now behaves like an Object?
Upvotes: 2
Views: 1384
Reputation: 2492
I think you’ve heard by now that Array is a type of Object, so I won’t beat that dead horse any further. Well maybe a little.
Which means you can accsss and set properties with names like “Monday” and “Tuesday”. Since it’s a type of Object this is no problem (and a statement like a[‘1’]
is implicitly converting that string ‘1’ to a number 1). But don’t mistake this property name to be an array index, those are specifically integers**. What’s the importance of that?
Arrays have a nice behaviour that when you use an actual array index, the length
property is automatically updated for you. Not to mention array index access is usually optimized by JVM implementations to be noticeably faster than regular property accesses.
Also let’s not forget one of the other huge benefits of having Arrays, they inherit from the Array.prototype, which has a whole lot of useful methods :)!
So in short use Arrays like Arrays — gain the perf boost while also making sure the code is easier to comprehend.
Source: JS Definitive Guide 6th - Array chapter
(** non-negative and less than 2^32-2 since arrays has 32-bit size indexes.)
Upvotes: 0
Reputation: 1518
Because in javascript there is no real Array
type as a low level type. Array
class is just a kind of a class which extended from Object
class.
Number
, String
ect. are extended from Object
class. So by doing this.
var ar = [] // I used array literal. Not totally same but similar of doing new Array();
arr['foo'] = 'bar';
You are just adding a new property to an object.
Upvotes: 0
Reputation: 6400
over all JavaScript array is also an object
if you check the type of x
typeof x
it will prints "object"
var x =[];
x.name = "X";
here we are creating a property "name" of x array
Upvotes: 0
Reputation: 4830
Everything in JS is an Object except the Primitive types (and even those come with Object wrappers)
That is why you can access properties and methods like array.length
array.indexOf()
etc just like you would with any other object. The indices are like special properties on the array object which are iterable
Upvotes: 0
Reputation: 24531
Because array IS an Object
[] instanceof Object
> true
[] instanceof Array
> true
Both give you true because Array extends normal Object functionality. Furthermore, the array indexes all its members by string values
const array = [];
array[0] = 1;
array['0'] // will give you 1
which is also unexpected by most of the people. So, the array behaves like an Object even if you use it as a normal array with indices
Upvotes: 8