I need some help with this, I'm stuck in JS Arrays & Loops, I don't know why this is telling me that if the function is empty is not returning "0".
function sumArray (numbers) {
// your code
var numbers = [1, 2, 3, 4];
if (numbers !== undefined) {
const sum = numbers.reduce((a,b) => a b, 0)
return sum
}
else if ( numbers === []);{
return 0
}
}
sumArray();
I tried to return 0 when the array is empty, but I' don't know what I'm missig.
CodePudding user response:
Beside the missing code, you could just return the result of reduce
.
return numbers.reduce((a, b) => a b, 0);
Some other annotations:
- Do not redeclare and assign
numbers
, because you the the array as parameter. - Do not check against
undefined
here, because you get always an array as parameter. - You can not check an empty array with comparing another (literally) empty array, because arrays are objects and you compare different object references. For checking if an array is empty, take
Array#length
property and compare against zero.
CodePudding user response:
The first issue is that you have a line ensuring that numbers is always an array containing 1,2,3,4
; so the empty condition will never be met. So that line needs to be removed.
A second issue is that you have an extraneous semicolon that is subtly changing the logic.
The following logic will run the empty statement if numbers
references the array object you just created using the array literal synax ([]
); then a block will be evaluated outside of the else..if
block, returning zero.
else if ( numbers === []);{
return 0
}
If you want to check if an object is an array you can use Array.isArray(foo)
.
If you want to check if an array is empty, you can test its length (if(myArray.length === 0) ...
)
So what you probably meant to write was:
else if (numbers.length === 0) {
return 0
}
...but it turns out that the reduce
code will work correctly if the array is of zero length; so that bit of logic is not necessary.
What you want is something like this:
function sumArray(numbers) {
if (!numbers) return 0;
return numbers.reduce((a,b) => a b, 0);
}
console.log(sumArray())
console.log(sumArray([]))
console.log(sumArray([1, 2, 3, 4]))