Let see how well do you know object iteration in Javascript. Have a look at the code samples below and predict the output. The solutions are post at the end with an explanation. It's recommended to try the problems on your own before you jump to the solutions section.


Problem #1

const obj = {
  33: "Jonas",
  54: "Dennis",
  5: "Brooke",
  batch: "2020",
  university: "TR"
};

for (const key in obj) {
  console.log(obj[key]);
}

A. Brooke Jonas Dennis 2020 TR
B. Jonas Dennis Brooke 2020 TR
C. 2020 TR Jonas Dennis Brooke
D. 2020 Brooke Dennis Jonas TR


Problem #2

Next, we change the order of keys: university and batch. What would be the output now?

const obj = {
  33: "Jonas",
  54: "Dennis",
  5: "Brooke",
  university: "TR",
  batch: "2020"
};

for (const key in obj) {
  console.log(obj[key]);
}

A. Brooke Jonas Dennis 2020 TR
B. Jonas Dennis Brooke TR 2020
C. Brooke Jonas Dennis TR 2020
D. 2020 TR Brooke Jonas Dennis


Problem #3

Now we randomly change the order of all keys. What would be the output now?

const obj = {
  54: "Dennis",
  university: "TR",
  5: "Brooke",
  batch: "2020",
  33: "Jonas"
};

for (const key in obj) {
  console.log(obj[key]);
}

A. Brooke Jonas Dennis 2020 TR
B. Dennis TR Brooke 2020 Jonas
C. Brooke Jonas Dennis TR 2020
D. 2020 TR Brooke Jonas Dennis


Answers

In an object, the keys are not ordered in the same sequence they are added to it. Instead, they follow a special ordering. With old Javascript engines the order was not guaranteed. But the order is pretty much standardised with modern Javascript engines.

There's just one rule that applies to all the problems above:

Integer keys are sorted in ascending order, rest of the keys follow the insertion order.

When we say integer keys, it does not exactly mean Integers. Objects keys are always strings (or symbols). So, even integer keys are strings.

What you need to look for here is that can the key be converted to a string and back to integer without the key getting changed. Look at the table below for a few examples.

Key (String) To Integer Back To String Is Integer Index
'1' 1 '1' Yes
'01' 1 '1' No
'1.5' 1 '1' No
'+1' 1 '1' No

Based on this rule, here are the solutions:

Answer#1: A. Brooke Jonas Dennis 2020 TR

Answer#2: C. Brooke Jonas Dennis TR 2020

Answer#3: C. Brooke Jonas Dennis TR 2020

If you do a console.log of the object in question, you can actually see the keys rearranged as per the rule above.

const obj = {
  33: "Jonas",
  54: "Dennis",
  5: "Brooke",
  batch: "2020",
  university: "TR"
};

console.log(obj);
{
  5: "Brooke",
  33: "Jonas",
  54: "Dennis",
  batch: "2020",
  university: "TR"
}

You can expect the same behaviour with other methods used to iterate over objects: Object.keys(), Object.values(), Object.entries()

I hope you learnt something new. For more Javascript challenges, don't forget to subscribe below.