Answer the question
In order to leave comments, you need to log in
Why not keep the state inside the function?
Let's take the function of finding the maximum number as an example:
function getMaxNumber(numbers) {
let maxNumber = numbers[0];
for (let number of numbers) {
if (number > maxNumber) maxNumber = number;
}
return maxNumber;
}
Answer the question
In order to leave comments, you need to log in
Bad store in terms of functional programming philosophy . After all, its meaning is in the mathematics of constructions.
The function you have is clean, but it is not in a functional style. Compare:
PS: I'm currently reading a book on FP in JS, I recommend it!
In this implementation, the function remains pure, because you do not store any state there.
But if you store state in a function, then the function will not be pure.
You won't be able to test it properly because you'll get different responses for the same input every time.
In essence, if the function is pure, then it doesn't matter what's going on inside. If using loops is easier or more productive, write through loops. The main thing is that there are no side effects (including reading / changing the global state). Yes, if you follow the principles of FP 100%, then mutable state should be abandoned altogether, but when programming in imperative languages, no one does this for a number of reasons, including the lack of syntactic sugar in such languages, familiar to functionalists, as well as possible performance problems (it is a question in the core just about use of a recursion instead of cycles, as in your case).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question