Wherefore art thou - return true statement

Tell us what’s happening:
I have been noticing (depending on the solution for the problem) in cases where the if statement is used inside loops, we return either true or false outside the loop block. In this solution, the ‘return true statement comes after the for-loop’ Kindly help me understand why it is the case i had to place the ‘return true’ statement after the loop. I often fall into the trap of placing such statements inside the loops for lack of understanding why.

  **Your code so far**

function whatIsInAName(collection, source) {
var arr = [];
arr = collection.filter(obj => {
  for(let i in source) {
    if(!obj[i] || obj[i] !== source[i]) {
      return false;
    return true;
return arr;

console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Wherefore art thou

Link to the challenge:

Hi @Wairua

What you are doing is checking for a condition inside the loop. If the condition evaluates to true, you stop executing the rest of the code in the function and return a value. If you execute the entire loop without the if condition evaluating to true, you exit the loop and then return another value.

For example in the function below, I will loop through the numArr parameter looking for even numbers. If I find an even number, I return true because my goal is to determine whether the array has an even number. If I complete the loop without finding an even number, I return false.

const hasEven = ( numArr ) => {
    for(let i = 0; i < numArr.length; i++){
        // If you find an even number return true
        if( numArr[i] % 2 === 0) return true;
    // The loop has been exited without finding an even number. 
    return false; 

console.log(hasEven([3, 5, 2, 7])); // true
1 Like

thank you so much for the quick and elaborate response.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.