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
}
}
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.
Note: Backticks are not single quotes.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
“” is a blank string and is not the value null. In what case are you needing to check if args is null?
When you are not sure what a variable’s value is, you should use console.log(thevariablename) to see what it is. It turns out that args is an array regardless of how many arguments are passed to the function. In this particular case, args would be an empty array. Think about an array property you could check which would indicate if args is an empty array, then your return 0; would work.
However, there is a much simpler solution. The reduce method has a second (optional) parameter which defines the starting value of the accumulator. What value could you use as the starting value of the accumulator? See the following reduce method documentation for how set the starting accumulator value.
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.
So as not to give you the final solution, I will show you how you could use reduce to calculate product of an array of numbers (while using the 2nd parameter of the reduce method).
var array = [1, 2, 3, 6];
function product(arr) {
return arr.reduce((prod, num) => prod * num, 1); // that , 1 at the end is the starting value for the accumulator (prod).
}
product(array); // 36
NOTE: I am not creating the product of the arguments of a function. I am just passing an array to create the product.