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

83
Visualizações
While loop not breaking out even if condition is false

A Javascript newbie here.

I was trying to make this simple program where the webpage will show the brute-force of any word you enter, every iteration. For now, I have limited it to console.log(). The code goes on something like this -

document.getElementById("intro").onclick = function(){
    alphabets = "abcdefghijklmnoqrstuvwxyz";
    text = alphabets[0];
    word = "foobar";
    i=0;
    j=0;
    for(i=0; i<word.length; i++){
        while(text.charAt(text.length - 1)!=word[i]){
            j++;
            text = text.substring(0, text.length - 1);
            text+=alphabets[j];
            //document.getElementById("word") = text;
        }
        console.log("found a matching letter!");
        j=0;
    }
}

Note:- if you've gone through the while loop, just ignore the fact that once it finds a matching word for the first character, it will not got to the next one as the length( of text) will end up being constant

Whenever this code is executed, it just goes into a state of an infinite while loop and makes the page completely unresponsive. I tried console.log(text) and it gives an output something like this -

enter image description here

Notice, how it doesn't console.log() the character p. So, I would expect it to exit the while loop that time and print the code outside the while loop(console.log("found a matching letter!"); and j=0;). But, in the picture above, as you can see, it doesn't get printed out. I then console.log(j) only to find it being printed continuously in an infinite loop while incrementing itself.

I honestly don't know what is happening or I'm missing something very obvious. Any help is appreciated. Thanks!

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