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

152
Views
Difference in output between While and For loop JavaScript - Newbee

It's a basic question; I can't seem to understand why in the code below the while loop output begins with 2 "#" and the for loop start with 1

Console Log Screenshot


let brick = "#";
while (brick.length < 8){

 brick += "#";
  console.log(brick);
}
console.log("For Loop");
for (let i = "#"; i.length <8; i+="#"){
 console.log(i) 
}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Because in the while loop, you are incrementing before and in the for loop after writing to the console.

Move your brick += "#"; to the end of the while loop and they will behave both the same way:

let brick = "#";

while (brick.length < 8) {
    console.log(brick);
    brick += "#";
}

For-Loop:

for (let i = "#"; i.length < 8; i += "#")
                                  ^ happens AFTER each iteration
about 4 years ago · Juan Pablo Isaza Report

0

You have already instatiated the brick at the start. But, when you are looping in the for loop the length is increased after the loop is finished. And the opposite is happening in the while loop.

about 4 years ago · Juan Pablo Isaza Report
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!