JavaScript While Loop Wheres The Count Variable -



JavaScript While Loop Wheres The Count Variable -

after comparing while , for loops, have question how while loop keeps track of count in sequence it's on. basic for loop goes this:

for (var = 0; < 5; i++) { console.log(i); }

so first time runs, i equals 0 fulfills status i less 5, executes block of code. increments variable i in next sequence i equals 1 satisfies status , on.

the while loop doesn't appear have variable stores sort of information. here piece of code found online.

function factorial(n) { var result = n; while (n > 1) { result = result * (n-1); n--; } console.log(result); } factorial(3);

so, after calling factorial(3), result equals 3 greater 1 code executes , result becomes 6. in next sequence, n equals 2 6 multiplied 2 minus 1 6 final output 6. question why isn't there n variable i variable in for loop? when loop decrements n, why isn't doing 3 minus 1 on , on again?

you said yourself: "when loop decrements n".

if n == 3 , decrement it, n equal 2 , on until equal 1, , status while (n > 1) evaluate false , loop stop.

javascript

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -