0

want to ask what is wrong with my code? The first log statement should return true but it returns false

// Returns whether or not the provided string contains a substring of "cake" in it.

function containsCake(string) {
  
  let testSentence = string.split(" ");
  
  for(let i=0; i < testSentence.length; i++){
    if(testSentence[i] ==='cake'){
      return true;
    } else {
      return false;
    }
  }

}


// Should return true
console.log("containsCake('I think cake is my soul mate.') returns: " + containsCake('I think cake is my soul mate.'));

// Should return false
console.log("containsCake('Pie is certainly the coolest dessert.') returns: " + containsCake('Pie is certainly the coolest dessert.'));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
dallenlee
  • 55
  • 3
  • 2
    When you do `return` your function exits/stops running, so your for loop only ever does one iteration. – Nick Parsons Jun 26 '21 at 14:09
  • use it - `function containsCake(string) { if(string.includes('cake')){ return true; } else { return false; }}` – s.kuznetsov Jun 26 '21 at 14:16
  • @s.kuznetsov why not just `return string.includes('cake');` ? – Robo Robok Jun 26 '21 at 14:20
  • @RoboRobok, well, that's okay too. – s.kuznetsov Jun 26 '21 at 14:27
  • It's not "okay too". Having `return true` and `return false` in an `if` is an anti-pattern. – Robo Robok Jun 26 '21 at 14:41
  • 1
    @RoboRobok bit strong to say it's an anti-pattern - it doesn't actively cause a problem. It's just a bit overly verbose, that's all. Perfectly reasonable thing for a beginner to write though while they're still getting their head around Boolean logic, returns etc – ADyson Jun 26 '21 at 15:26

0 Answers0