DEV Community

Discussion on: Don’t pay the for-loop tax

Collapse
 
julienetienne_ profile image
Wolfie's just fine • Edited

for-loop-tax is accompanied with an array-method-tax.

I agree the first go-to should be array-methods, even with objects "for in" usually sucks compared to Object.keys(foo).map((propName,i)...) as you get i included.

The exceptions IMO are performance, break, continue and return.

It requires discretion because in some circumstances you could sometimes be writing spaghetti code when trying to be too functional where break, continue & return "sometimes" result it far less code and better maintainability (sometimes). But obviously vice versa as you've demonstrated.

Collapse
 
mike1808 profile image
Michael Manukyan

Never rely on the order of keys of objects in JavaScript because by specification the interpretator can order them as it wishes

Collapse
 
julienetienne_ profile image
Wolfie's just fine • Edited

Not for generic prop names but if you previously "created" incremental prop names:

const obj = {thing-0: 'thing-a', another-thing-1: 'thing-b', 'something-2: 'thing-c'};
...
... obj[key.value.slice(0,-1) + i] // do something

There could also be situations where you need to accumulate based on the number of props rather than specifically the order of props.