I 100% agree with mantra here, but I'd like to add to the examples. For me, the functional style/indirection in these examples IS the value, and once you're doing things in a functional way you've already captured most of the technique's purpose. For me, whether you continue to use a declarative iterator or a for loop inside your abstraction is less important.
Here's an admittedly naive example of the price discounting that I think very clearly shows the difference between a for loop and an Array.forEach.
letprices=[5,25,8,18];letdiscount=1-0.2;// more imperativefor(leti=0;i<prices.length;i++){console.log(prices[i]*discount)};// more declarativeprices.forEach((price)=>{console.log(price*discount);});
Just reading these aloud to yourself shows the difference in clarity:
"For when i equals zero and i is less than the length of prices while incrementing i, console log prices at position i times discount."
vs.
"Prices: for each price, console log price times discount".
When moving from an imperative to declarative style, the code turns from near gibberish to an honestly comprehensible English sentence. I think that's a win for the whole team at every skill level, and the value this style is attempting to capture.
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.
I 100% agree with mantra here, but I'd like to add to the examples. For me, the functional style/indirection in these examples IS the value, and once you're doing things in a functional way you've already captured most of the technique's purpose. For me, whether you continue to use a declarative iterator or a for loop inside your abstraction is less important.
Here's an admittedly naive example of the price discounting that I think very clearly shows the difference between a
for
loop and anArray.forEach
.Just reading these aloud to yourself shows the difference in clarity:
"For when
i
equals zero andi
is less than the length ofprices
while incrementingi
, console log prices at positioni
times discount."vs.
"Prices: for each price, console log price times discount".
When moving from an imperative to declarative style, the code turns from near gibberish to an honestly comprehensible English sentence. I think that's a win for the whole team at every skill level, and the value this style is attempting to capture.