map with side effects… yes, that's bad practice. But one could use map here. It might not be necessary in the trivial case, but if we want to throw a filter in there as a sanity check, this makes for readable code:
constfruitIds=['apple','orange','banana','carrot'];// carrot is not a fruitfruitIds.map((id)=>document.getElementById(`fruit-${id}`)).filter((element)=>!!element).forEach((element)=>element.classList.add('active'));
const fruitIds = ['apple', 'orange', 'banana', 'tomato']; // tomato is a fruit
fruitIds.forEach((id) => {
const element = document.getElementById(`fruit-${id}`);
element?.classList.add('active');
});
Is that not equivalent, clear, and only iterates the list once instead of ~3 times?
What are the pros and cons of chaining array methods like the above? Perhaps easier to add another method, eg sort(), or some other filter()...but in this instance, not so much, imo.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
map
with side effects… yes, that's bad practice. But one could usemap
here. It might not be necessary in the trivial case, but if we want to throw afilter
in there as a sanity check, this makes for readable code:Why not just the following?
Is that not equivalent, clear, and only iterates the list once instead of ~3 times?
What are the pros and cons of chaining array methods like the above? Perhaps easier to add another method, eg
sort()
, or some otherfilter()
...but in this instance, not so much, imo.