Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda