Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!