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

82
Views
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
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!