1

To confirm that the array is just a specific type of object, I've written some code to get ensured.

let obj = { 0 : 10, 1 : 11, length : 2 }

Object.setPrototypeOf(obj, Array.prototype)

console.dir(obj)

obj[5] = 15

console.dir(obj)

Seeing the log of first console.dir

I thought I had made a perfect array [10, 11].

So I put a new element in, and checked if the length property was changed. ( just like an array )

But it didn't.

I'm wondering what the difference of obj above and [10, 11] is.

Furthermore, I'm quite curious how an array can always refresh its length property whenever the elements of it change.

Thank you for hearing my concern.

kwonryul
  • 481
  • 3
  • 10
  • 1
    Please check this for first question's answer : https://dev.to/zac_heisey/objects-vs-arrays-2g0e#:~:text=Objects%20represent%20a%20special%20data,store%20a%20list%20of%20values. – Harmandeep Singh Kalsi Jun 25 '20 at 18:16

1 Answers1

1

Iterator

Arrays and your object with number keys differ mainly because arrays have some functions already present in their prototype, and also (particularly) they have an iterator:

You can define and add the iterator to an object, and it will then behave similarly with a for .. of loop.

Learn more about iterators here.

Length

As you noticed, length was not updated in your object. Array#length is indeed a property that is is actually updated to keep the "number" keys in the array. You could probably forge it yourself by creating such a property, I may be wrong but I don't see anything impossible at first sight.

Properties can be a complex functions (getter and setter) hidden in some name that looks like a field.

See here for instance to learn more about properties.

I'm not going into more details in this answer, but there are ways in JavaScript to "hook" complex logic whenever some key is added (it's rarely used by most developers, but it exists.)

If you're curious about the arcane of JavaScript, and the many esoteric things you can do with the language, I strongly recommend that you read the section on objects and the one on ES6 from the e-book "You don't know JS" by Kyle Simpson. (1st edition is open source):

Built-in literals

Sorry for stating the obvious, but they have built-in literals in the language. And this, you cannot "forge" (a new literal for a particular special object that you designed).

They have a special place in ECMAScript specs

In case you don't know, JavaScript is a normalized language, an implementation of the ECMAScript standard.

There is whole section concerning arrays, so they indeed have a particular place in JavaScript.

Here is the link

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Pac0
  • 21,465
  • 8
  • 65
  • 74