Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda