0

I'm new to JavaScript and I'm not finding any solid info on what the order is on a for...in loop, specifically in the problem I've solved for below

Problem:

Write a function called minMaxKeyInObject that accepts an object with numeric keys. The function should return an array with the following >format: [lowestKey, highestKey]

Solution:

function minMaxKeyInObject(obj){
  arr = []
  newarr = []
  for (key in obj){
    newkey = parseInt(key)
    arr.push(newkey)
  }
  newarr.push(arr.pop())
  newarr.unshift(arr.shift())
  
  return newarr
}

Result:

minMaxKeyInObject({ 9999: 'a', 120: 'b', 100000: 'c', 98: 'd', 50: 'e' }) 
// [50, 100000]

I'm not looking for any edits to my solution, I'm hoping to learn more about why the keys are pushed in numerical order despite being strings.

  • 2
    Sadly, the best answer is, that's just how it works. In practice, it's not a good idea to rely on the order of object properties for reasons like this. If you need to preserve the order of object keys, you'd probably be better off with an array as your data structure instead. – Alex Wayne Sep 28 '21 at 17:16
  • 1
    the order of keys is defined by following order: positive 32 bit integer comes first in order, then all other values except symbols in insertation order. symbols comes at last in insertation order. – Nina Scholz Sep 28 '21 at 17:16

0 Answers0