Need code explanation for challenge with the every method

Hi

I’ve just completed this challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria

My first attempt didn’t pass the tests

function checkPositive(arr) {
  // Add your code below this line
  arr.every(function(currentValue) {
      return currentValue > 0;
  })
  
  // Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);

This was the error message I got:

// running tests
checkPositive([1, 2, 3, 4, 5]) should return true.
// tests completed

I then used this tool http://pythontutor.com/javascript.html#mode=edit to see, what was going on. It turns out that whenever the array had negative numbers it would correctly return false at the first negative number found in the array. However, when the array had only positive numbers it would evaluate all of them to true and then return undefined.

I fixed this issue by adding another return statement outside the every() method. Like this:

function checkPositive(arr) {
  // Add your code below this line
  let result = arr.every(function(currentValue) {
      return currentValue > 0;
  })
  return result;
  
  // Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);

This time all tests passed. By now I should be happy with my result, but I don’t get why the first solution failed. I even looked at the hints section and the solutions in that section did exactly what I did the first time around. Is it a specific browser issue? I used Mozilla 67.0.1 for this challenge.

Apparently I don’t know how to use the spoiler tag either. Sorry.

The every method works in both cases. The issue is that the checkPositive function doesn’t have a return statement so it returns undefined by default.
You can even do it as one liner return arr.every(...)

The spoiler tags are to be put outside the backticks, I am fixing that for you

Thank you for fixing my spoiler tags :slight_smile:
Come to think of it I’ve probably been using return statements for every function up until now. I think what threw my off in this challenge, was the fact that the checkPositive function didn’t need the return statement when the array had negative numbers, which logically seems inconsistent to me.

I think it is because in that case you are returning a falsy value anyway (undefined instead of false) and it could be throwing off the tests

1 Like

Yea, that makes sense. Thanks for helping out!