TIL the problem with using Loops
POSTED ON:
TAGS: math loops javascript
Loops tend to have some flaws.
Loops include
for
forEach
while
do
for...of
for...in
What is the problem with Loops: #
Off by one error #
An off-by-one error is when you expect something to be of value N, but in reality it ends up being N-1
or N+1
.
For example, you were expecting the program to perform an operation 10 times, but it ends up performing 9 or 11 times (one too few or one too many times).
More details in this post
Infinite Loops #
For loops, with a wrong typo, can keep going without stopping.
Statefulness #
Loops keep state.
More details in this post
Hidden Intent #
Loops can obscure what it was designed to do.
Alternatives to Loops #
Recusion #
To solve off by one
errors and statefulness
, you can use recusion.
BUT both loops and recursions do a poor job of signalling intent.
More details in this post
Higher Order Functions #
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. The term comes from mathematics, where the distinction between functions and other values is taken more seriously. Higher-order functions allow us to abstract over actions, not just values. They come in several forms.
Higher-order functions like Map, filter, fold and friends package up common recursive patterns into library functions that are easier to use than direct recursion and signal intent.
More details in this post
More advanced methods (and way outside of my knowledge level) are these methods.
Corecusion #
Transducers #
Monoids #
F-Algebras #
REFERENCES:
https://github.com/you-dont-need/You-Dont-Need-Loops
https://thenewstack.io/4-reasons-not-to-use-programming-loops-and-a-few-ways-to-avoid-them/
Related TILs
Tagged: math