Reputation: 909
I have a quick question on why my function is returning false, when I expect it to be returning true. I have looked at the documentation for Array.prototype.every, and I still can't seem to find it. Thanks for your help in advance.
For some context, this is part of a coderbyte question called arithGeo. The current function I am working on here is supposed to return true if the difference between each element is the same. Here, I expect this to return true, since each element is 5 apart from the next.
Here is my function
var arr = [5, 10, 15];
function isArith(arr){
var diff = arr[1] - arr[0];
return arr.every(function(val, ind, col){
// if statement checks to make sure I stay in bounds.
if(col[ind + 1] !== undefined){
var next = col[ind + 1] - val;
console.log(diff === next );
// logging shows the following statement to be true, for every iteration
return diff === next;
}
});
}
var arith = isArith(arr);
console.log('arith: ', arith) // logs false
Upvotes: 0
Views: 1205
Reputation: 198334
When you reach the last element, you test to see if there is a next element so you don't compare the last element with nothing. That's great. But in that case, you forget to return
anything, and the default return
is undefined
, which is falsy. Just put in else return true
.
Upvotes: 2
Reputation: 413737
On the last iteration you'll return undefined
, which will be interpreted as false
. The code does that because if the if
fails (which it does on the last element) there's no return
statement. If you add return true
to the end after the if
it should work.
Upvotes: 3