As someone who doesn't really use JavaScript much, what was wrong with the function declaration form and why are the rest needed? I learned JS before the newer ways existed and never really kept up.
The function expressions can be inlined (you define them where they are used) and if you are going to inline them anyway, it's better to be as concise or as short as possible:
const sumOfSquaresOfEvens = nums
.filter(x => x % 2 === 0)
.map(x => x * x)
.reduce((x, y) => x + y)
You could declare those 3 functions beforehand but what's the point in declaring one-liner functions?
I’m sure you meant the opposite of what I’m about to say but declaring three functions is generally much more complex and less readable than just chaining array methods
I get what you mean, it’s totally appropriate for VERY simple operations to be chained, but overall functions should be as short and simple as possible.
You should absolutely not have 120 line functions that carry out a multitude of operations.
Of course it depends on the situation, but if the function is only being used in that one place it makes sense that it’s not defined but just written inside of a chained array method. Otherwise you’re forced to jump around a file searching for functions by name. Much more readable to just start at the variable name “sumOfSquaresOfEvens” and read what it does where it’s doing it.
Of course I do. I split up my code into functions where it makes sense to do so. sumOfSquaresOfEvens is a simple function. In this case you aren’t going to test each individual method inside of the chain. You are going to test the entire thing together.
But that’s not what the original post was suggesting, it had an inline sumOfSquaresOfEvens.
If that is inline, I’m gonna go ahead and assume the containing function is unacceptably complex. The poster asked why that function should be broken out as opposed to inlined and I suggested for testing and readability.
I guess it would be ok to just slam in a bunch of inline functions and test the inputs outputs depending on your requirements, but typically I’m not writing code with the intention of it being used in only one place. Inevitably this leads to an unmanageable mess.
What happens when we switch the algorithm for calculating the number? You go and change that inline function all over your code? Na
Right it definitely depends on the situation and if the code is used in multiple places then breaking it out into functions isn’t just good practice it’s a necessity.
38
u/damnNamesAreTaken Apr 14 '24
As someone who doesn't really use JavaScript much, what was wrong with the function declaration form and why are the rest needed? I learned JS before the newer ways existed and never really kept up.