# For... in... is iterating wrong

In this code:

``````function convertToRoman(num) {
var pairs = {
1000: 'M',
900 : 'CM',
500 : 'D',
400 : 'CD',
90 : 'XC',
50 : 'L',
40 : 'XL',
10 : 'X',
9 : 'IX',
5 : 'V',
4 : 'IV',
1 : 'I'
}
var romanNumeral = ""
for (var value in pairs) {
console.log(value)
while (num >= value) {
romanNumeral += pairs[value]
num -= value
}
}
console.log(romanNumeral)
}

convertToRoman(36);
``````

When I console.log(value ), I get 1,4,5,9,etc. I want it in reverse order. No matter where I put the â€ś1â€ť in the object it always gets output first. Why is this and how do I fix it?

Thanks,

Andrej

You have no control over the order in a forâ€¦in loop.

So how would you gain control??

If order matters, you need to get the keys array and sort it yourself.

1 Like

You could use a map structure as well (instead of objects), that makes a fairly easy fix for you. Look it up in the JS reference of your choice.

1 Like

As long as it conforms to the current spec, order should be guaranteed. But the current spec is this year, so not full support yet. Even then, it may not be the order you expect (see the `[[OwnPropertyKeys]]` internal method, which now all object iteration methods should conform to) â€“ the order is:

• integer keys in ascending order, then
• string keys in insertion order, then
• symbol keys in insertion order.

You have a set of integer keys, so the only guarantee you can get is to use a method like `Object.keys` which is in all browsers and exhibits the guaranteed order behaviour. In that case itâ€™ll produce them in ascending order, not how youâ€™ve written them.

JS provides a data structure (`Map`) that does always retain insertion order, you can use that instead of a plain object.

3 Likes