please can you help me understand when and under what conditions should I be returning more than once in a statement block? for example, my code:
function checkPositive(arr) {
return arr.every(function(element) {
return element > 0;
});
}
why does this only work if I return twice?
I'm confused about how to follow this structure and when to know I should be using them.
Thanks
CodePudding user response:
Since your code has two functions, and a return
only applies to the function that return
is a member of, you need two return
statements.
It may become more clear when you first define the inner function and then the outer function:
function isPositive(element) {
return element > 0;
}
function checkPositive(arr) {
return arr.every(isPositive);
}
The only difference here, is that we have given a name to the inner function (isPositive
) using a function
statement.
In this particular case, the isPositive
function returns whether a single value is positive, while checkPositive
returns whether all values are positive. These functions have a different purpose, and thus are responsible for returning what they are intended to evaluate.