This code does not work for the instance where the “” argument is passed into sum. Please explain why.
function sum (...args){ //creates sum function
if (args === ""){ //determines if argument passed is null
return 0; //returns 0
} else {
return args.reduce((a, b) => a + b); returns sum of all arguments passed into sum
}
}
The code I have written passes all parameters except the following:
sum();
I guess first question, if this argument is not null then what is it? (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null)
I thought so but then my problem is still the aforementioned condition:
function sum (...args){
return args.reduce((args = 0, b) => args + b);
}
function summ(...args) {
return args.reduce((a, b) => {
return a + b;
});
}
}
I have tried both of these lines of code and am still getting errors with
sum();
Let me try to explain how I am looking at this so you can tell me what I don’t understand:
var arr1 = [1, 2, 3, 6];
const sum = (a, b) => a +b;
arr1.reduce(sum, 4); //16
This is because the reduce function is applying the sum function to all elements of arr1 and the initial value, 4.
Now applied:
function sum (...args){ //creates sum
const add = (c, d) => c + d; //creates add
return args.reduce((add, b = 0) => add + b); //runs add and reduce functions on the array args, initial value is 0
}
console.log(sum(12,2)); //14
console.log(sum()); //Error: Reduce of empty array with no initial value
It is because of this error that I tried using the if statement to filter out the condition to at the beginning.
Thank you very much @camperextraordinaire!