Tell us what’s happening:
When I change the input manually the console is returning the right values for all of the inputs, but when I run the test one of the tests fails (For the array of all positive numbers)
Your code so far
function checkPositive(arr) {
// Add your code below this line
var x = arr.every((x) => {return x >= 0});
console.log(x); // Add your code above this line
}
checkPositive([1, 2, 3, 4, 5]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
.
Link to the 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
It’s because you aren’t returning anything out of the function, and when that happens the function returns undefined
which is falsey (JavaScript interprets it as false). So you are passing those tests by accident.
instead of console.log(x)
you want return x
console.log()
does not actually return data. It just displays (or logs) data on the console.
2 Likes
function checkPositive(arr) {
// Add your code below this line
var x = arr.every((x) => {return x >= 0});
return x;
// Add your code above this line
}
checkPositive([1, 2, 3, 4, 5]);
Here’s a bonus for you. With a function like this where you aren’t using the results of arr.every()
inside the function, you can just return it directly:
function checkPositive(arr) {
// Add your code below this line
return arr.every((x) => {return x >= 0});
// Add your code above this line
}
And, for that arrow function inside the Array.every()
, if an arrow function is just a single expression you don’t need the brackets or the return
function checkPositive(arr) {
// Add your code below this line
return arr.every((x) => x >= 0);
// Add your code above this line
}
And, to blow your mind even more, when that arrow function only has one parameter (the x
in this case) the parentheses around it are also optional:
function checkPositive(arr) {
// Add your code below this line
return arr.every(x => x >= 0);
// Add your code above this line
}
1 Like
This is a stellar and thorough response to the subject! Props
!
1 Like
Fantastic! this actually clears up alot for me on arrow functions. I have had a few instances where I used the format in your final example with no success(I now know why), so I started including the parentheses and brackets not knowing why the heck it worked sometimes and not others!