0

const arr = [4, 3, 2, 7, 8, 2, 3, 1];

let object = {};
object[arr[4]] = 0;
object[arr[3]] = 0;
object[arr[7]] = 0;

console.log(object)

check this out

Why are the keys of the object not in the chronological order? I thought the output would be something like this{0: 0, 1: 0, 2: 0}

Mister Jojo
  • 12,060
  • 3
  • 14
  • 33
Fitri Rozi
  • 43
  • 6
  • "I thought the output would be something like.." - what reference documentation leads to that conclusion? Read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects eg. What documentation *doesn't specify* is as important to keep in mind as what it *does*. – user2864740 Jan 16 '20 at 23:51
  • 2
    "chronological order" --- a JS object is a collection of key-value pairs, you specified the keys and their corresponding values. – zerkms Jan 16 '20 at 23:54
  • I'm just confused about why the properties are not in chronological order. If it was an array, then that would be the case, right? – Fitri Rozi Jan 16 '20 at 23:54
  • An object is not an array so.. wouldn't expect a fish to have legs either. – user2864740 Jan 16 '20 at 23:55
  • Well, an array is an object. – Fitri Rozi Jan 16 '20 at 23:55
  • According to the ES6+ specs, the order of integer keys is ascending. Just like with arrays. – VLAZ Jan 16 '20 at 23:56
  • An array is an object indeed. `let object = {};` - this is not an array though. – zerkms Jan 16 '20 at 23:56
  • all objects are not array – Mister Jojo Jan 16 '20 at 23:56
  • 1
    @FitriRozi And? That is the *same logical error* as this: A human is a mammal. Humans can speak. Therefor mammals can speak. – user2864740 Jan 16 '20 at 23:56
  • 2
    Does this answer your question? [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – gforce301 Jan 16 '20 at 23:56
  • The bigger question is why does it matter to you? If you want things in a certain order that is why arrays exist. – gforce301 Jan 16 '20 at 23:58
  • @gforce301 also, Map - that preserves insertion order by spec. – VLAZ Jan 16 '20 at 23:58
  • Okay, I get it now. When iterating over map object, it returns keys in order of insertion – Fitri Rozi Jan 17 '20 at 00:20

0 Answers0