'How can I rewrite a break statement in a for loop using only if/else statements in Javascript?

I am working through a Javascript course and am currently learning about break statements in for loops. The course text says that I can instead write if/else statements instead of using the break statement to accomplish the same thing. I have a solution, but it was difficult to come up with and it seems like a rather inelegant solution too.

Code using the break statement:

var numsArray = [1, 2, 3, 4, 5];

// stipulation: do not print out elements with index value greater than 2
for (var i = 0; i < numsArray.length; i++) {
  if (i > 2) {
    console.log('FOR LOOP BROKEN');
    break; // ends loop
  }
  console.log('current index:', i);
  console.log('current element:', numsArray[i]);
  console.log('==============');
}

Code rewritten to only use if/else statements:

var numsArray = [1, 2, 3, 4, 5];

// stipulation: do not print out elements with index value greater than 2
for (var i = 0; i < numsArray.length; i++) {
  if (i > 2) {
    console.log('FOR LOOP BROKEN');
    i = numsArray.length; // ends loop
  } else {
    console.log('current index:', i);
    console.log('current element:', numsArray[i]);
    console.log('==============');
  }
}

This works, but I feel like there should be a better way to make sure the loop doesn't run the statements after the if statement block. Is there?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source