Search code examples
javascriptfor-loopbreakcontinue

for loop using break and continue


I'm writing a for loop that needs to push no more than three elements to the array 'bag,' and use 'break' to jump out of the loop when 'bag' is full with said three elements. So far my code passes three out of the four tests. The issue I'm encountering is that for the fourth test, which should be where the code 'breaks' and the loop stops running, that instead, a fourth element is getting pushed to my 'bag' array. If 'bag' isn't full I need to traverse 'dolls' until the last element.

I'm a total beginner and I've tried a couple different things, but I can' figure out what I'm doing wrong. The code I have is below.



function grabDoll(dolls){
  var bag=[];
  //coding here
  for (let i = 0; i < dolls.length; i++) {
    if (dolls[i] == 'Hello Kitty' || dolls[i] == 'Barbie doll') {
      bag.push(dolls[i])
    } else if (dolls[i] == '') {
      continue;
    } else if (bag.length - 1 === 2) {
      break;
    } else continue;
  }
  return bag;
}

Solution

  • You need to change your code to this

    function grabDoll(dolls){
      var bag=[];
      //coding here
      for (let i = 0; i < dolls.length; i++) {
        if(bag.length === 3) {
          break;
        } else if (dolls[i] == 'Hello Kitty' || dolls[i] == 'Barbie doll') {
          bag.push(dolls[i])
        }
      }
      return bag;
    }
    

    Your code will only check the else if's if the if or else if that came before it results to false. I.e if if (dolls[i] == 'Hello Kitty' || dolls[i] == 'Barbie doll') resolve to true, your code won't check the else if related to that if. Also, you don't need the command continue to continue the loop. When the loop reachs the end, it'll check the loop condition again, if it resolves to true, the loop run again, otherwise, the loop stops. So you don't need this part

    } else if (dolls[i] == '') {
          continue;
    

    nor this

    else continue;