Performance-wise, I would say there is no difference, but for readability and for the ability for code re-use, I would say it is better to create the separate function. Having a separate function allows you to call it from multiple places, but only define it one time.
Anytime, you can make your code more readable and not take a performance hit, I would always go with the more readable version.
I was questioning whether to start a different thread or not… but since this one is here and asking a similar one I will ask anyway…
Would it work to further refactor this code into something like :
const sum =sum+>sum(...args){
return args.reduce((a,b)=>a+b,0); }; ```
Or would that possibly hose the reduce function for lack of proper "function " return ?
Also , let me know if I should have put this into another post instead of here I will be happy to move it..
Thank you !
The parentheses cause the outer function to execute (thereby returning the inner function “sum”).
This construct (the surrounding function) is interesting in and of itself. It’s called an IIFE (immediately invoked function expression). Often used to create a private scope for the returned function.
Try googling IIFE (or its expansion) to find out more.
I am a beginner and I hope not to mislead you… but for what I know this sintax is useful in order to define a function and call it at the same time.
For instance you can replace this code :
const test = function(){
console.log("You need to call me !") ;
} ; // display nothing
test() ; // display the text
By this code
(function(){
console.log("You do not need to call me !") ;
})() ; // display the text
That said, I don’t know yet why FCC chose to use it in this one exercise.
I now understand the solution, however what is the point of the comma 0, as was in the original question. I ran the code without comma zero, and it worked the same.
But I don’t understand why or the purpose of comma zero. Sorry if this question is not directly related to function parameters, but the comma zero is on my mind.
reduce accept a second argument, which is the starting value of the accumulator. if not specified the starting value of the accumulator is the item at index 0
awwwwsomeee! that makes sense, i tried it with starting value of 5, and it added 5 to the total. thanks so much i appreciate the cool way you explained it
you should use MDN at first, try to understand the syntax, take a look on all examples, type it yourself to see what happen, etc and you will learn a lot.