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.
When function is a statement, it has the same binding rules as var. When it is an expression, a name is optional but if it is provided it is scoped to the function body. The fat arrow operator is just like a function expression accept it does .bind(this) at the end and can have an expression instead of a code block for a body.
JavaScript has a lot of warts, but the way it lets one sling functions around …. I just love it.
They are handled differently by the compiler when it comes to where the function is scoped in memory. Variables are treated like other variables rather than globally like a traditional function.
A series of short gasps were heard, and the room fell silent as all eyes turned to /u/SparserLogic. Did they really know JavaScript, or are they an undercover desktop C programmer person trying to infiltrate the sub?
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.
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.