0

From the document for forInRight:

This method is like _.forIn except that it iterates over properties of object in the opposite order.

Why lodash need to have 2 functions which do the same things, except orders, but iteration order is not guaranteed?

5413668060
  • 196
  • 15
  • Iteration order of object properties is pretty much guaranteed in modern JavaScript. – Robby Cornelissen Sep 04 '19 at 03:45
  • The example code for `_.forInRight` has a nice little note... _"Logs 'c', 'b', then 'a' **assuming `_.forIn` logs 'a', 'b', then 'c'**"_. So whatever order `_.forIn` produces, `_.forInRight` will do the opposite – Phil Sep 04 '19 at 03:47
  • @RobbyCornelissen I have tried for many browsers and node and what you said is true. However it is what the doc stated. What is the case that is not guaranteed? – 5413668060 Sep 04 '19 at 03:49
  • @Phil I know the effect but the main point is as iteration order is not guaranteed, why need two different functions. – 5413668060 Sep 04 '19 at 03:50
  • [This answer](https://stackoverflow.com/a/38218582/3558960) summarizes it pretty well I think. – Robby Cornelissen Sep 04 '19 at 03:52
  • `forIn`/`forInRight` also used on Arrays ... order in Arrays **is** guaranteed, so you may want to iterate through from end to start - if you don't trouble yourself concentrating on where it's not obviously useful, you'll see that having both is extremely useful – Jaromanda X Sep 04 '19 at 03:52

1 Answers1

0

You cannot guarantee iteration order because the keys in an object should not be assumed to a sorted set, in other words, different engines are not required to keep an order on the keys.

However, if your engine does try to preserve the order in the keys, this method lets you iterate them backwards. It can't guarantee that it will be what you expect, but it attempts to do so. It'd be similar to doing something like Object.keys(yourObj).reverse().forEach(...)

arg20
  • 4,548
  • 1
  • 45
  • 70
  • See [here](https://stackoverflow.com/a/5525820/3558960). ECMAScript 2015 dictates iteration order pretty definitively for most cases. I still wouldn't rely on it, but for very specific use cases. – Robby Cornelissen Sep 04 '19 at 03:48