Thursday, August 1, 2019

JavaScript: while loop inside a for loop

var hash = "";
var count = 1;
var n = 3;

for (var pound = 1; pound <=7; pound ++)
{while (hash.length != count)
hash += "#";
hash += "\n";
count += n;
n ++;}
console.log(hash);


Hi, I'm new to Javascript and fairly new to coding in general. I've spend a couple of hours analyzing my code above. BTW, I generated myself without any assistance. I wouldn't say I'm proud because I dont know why or how it works. I guess I get the basic math behind the work and when I check the values of the variables at the final end, the results match my calculation. But I dont know exactly what happens. It generates a triangle using '#'. I've tried removing the For loop to see exactly what the while loop is doing but I cant get a hang of it. Please take a look.




At first, in the first For loop and coming into the while loop, the value of hash.length is 0. Comparing it to count which 1, they do not match and so nextline. After adding "#" and "\n", hash.length becomes 2. But the code is read to the end making var count now 4 and var n equal to 4 also.



Now, the next loop does not happen inside the while loop and I've tried this out myself. It goes back to the For Loop. Checking the condition of "hash.length != count", this condition still holds as hash.length is 2 and count is now 4. Since they are not equal, shouldn't the while take repeat before going back to the For loop again?

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...