0

I created the following object.

But why do the numbers appear before the letters, when printed.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false,
  3: '3',
  e: 'e',
  4: 't'
};

object1.d = 'something';
object1.z = 'another thing';


console.log(Object.keys(object1));
// > Array ["3", "4", "a", "b", "c", "e", "d", "z"]
Darth
  • 1,238
  • 8
  • 15
Grateful
  • 7,657
  • 7
  • 34
  • 59
  • See [this answer](https://stackoverflow.com/a/58444013/5648954) specifically from the above link – Nick Parsons Aug 24 '20 at 09:16
  • Unless I've misunderstood the provided link, it just seems to mention that keys are not in order and that various browsers list them differently. Is this correct? So basically, there is no answer to the question 'why'... It's just how things are! – Grateful Aug 24 '20 at 09:23
  • In the newer spec (ES2020), Object.keys will return properties in the order of numeric keys (in a particular range), then all other non-symbol keys in the order they were inserted into the object, and then the Symbol keys in the order they were inserted. Older browsers which are using out of date engines that aren't following the latest spec won't neccessarly follow this order, so it probably shouldn't be something that you rely on. – Nick Parsons Aug 24 '20 at 09:28
  • Unordered data structures should not be depended on to have any order. In javascript it used to be that every browser had a different implementation depending on what optimization they want to implement. Firefox was the last to implement the current ordering behavior after being pushed by (IMHO misguided) developers. In the go programming language the language designers felt strongly enough about this that they implemented a random number generator so that maps always return their keys in random order to discourage people depending on the order of unordered data structures – slebetman Aug 24 '20 at 10:12

0 Answers0