1

I am confused about how JavaScript seems to implement some sort of default sorting when the keys of an object are initially inserted as numbers (before being typecast as strings):

let myObj = {2: 'ant', 3: 'bee', 1: 'cat', shark: 'shark', mouse: 'mouse'}
console.log(myObj); // { '1': 'cat', '2': 'ant', '3': 'bee', shark: 'shark', mouse: 'mouse' }
// Expected: { '2': 'ant', '3': 'bee', '1': 'cat', shark: 'shark', mouse: 'mouse' }

The context I first noticed this was when building a "frequency object" for an array of numbers:

function frequencies(nums) {
  return nums.reduce((acc, num) => {
    acc[num] = (++acc[num] || 1);
    return acc;
  }, {});
}

const stringsExample = frequencies(['cat', 'dog', 'cow', 'cow', 'dog', 'ant', 3, 1, 2]);
console.log(stringsExample); // { '1': 1, '2': 1, '3': 1, cat: 1, dog: 2, cow: 2, ant: 1 }
// Expected: { cat: 1, dog: 2, cow: 2, ant: 1, '3': 1, '1': 1, '2': 1 }

const numbersExample = frequencies([5,5,5,3,4,5,6,2]);
console.log(numbersExample); // { '2': 1, '3': 1, '4': 1, '5': 4, '6': 1 }
// Expected: { '5': 4, '3': 1, '4': 1, '6': 1, '2': 1 }

I have not found anything online that explains what causes this behavior. Can anyone explain what is happening here?

Daniel W. Farlow
  • 222
  • 4
  • 11
  • Objects are inherently unordered. Don't use them when you need a specific order. That said, yes (modern) engines use a standardised ordering for reproducibility. – Bergi Apr 07 '20 at 17:51
  • ojects have a defined order (with the actual version) of first number who could be an index of an array (positive 32 bit integer), strings/other numbers in insertation order followed by symbols. – Nina Scholz Apr 07 '20 at 17:51
  • Its more a behavior of the console – Anurag Srivastava Apr 07 '20 at 17:51
  • I'm not aware of any default sorting behavior on object keys. That's why when ever you see a question about maintaining order of object keys it is explained that order cannot be guarenteed. It is effectively up to the javascript engine implemented by each browser to do whatever it deems most efficient towards object key storage and retrieval. – Taplar Apr 07 '20 at 17:52
  • @Bergi I realize objects are inherently unordered (hence my question). I don't need a specific order. I am only curious about the behavior. This is in the context of later using `Object.entries` and trying to understand how my object is stored. **Edit:** Okay, your note about engines using standardised ordering for reproducibility may be what's causing this possibly. – Daniel W. Farlow Apr 07 '20 at 17:53
  • 1
    @Daniel see the answers to the duplicate about that, explaining this ordering in detail. – Bergi Apr 07 '20 at 17:54
  • @Bergi Thanks! Your link answers my question. Appreciate the pointer. – Daniel W. Farlow Apr 07 '20 at 17:56

0 Answers0