0

I'm a newbie in Javascript and I need to learn how this simple code that I just saw somewhere in the internet works:

var f = 1;
var i = 2;

while(++i<5) {
    f*=i;
}

console.log(f);

Can anybody help me understand how this loop works?

1

3 Answers 3

3

Check comments to understand it:

var f = 1;
var i = 2;

while(++i<5) { //will increment first and then check if the incremented value is less than 5

    f*=i; //can also be written as f = f*i
}

console.log(f);

First iteration:: while (3<5) it will make f = 1*3 which is 3

Second iteration:: while (4<5) it will make f = 3*4 which is 12

Third iteration:: while (5<5) which is false so loop will stop

Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure :) You can mark the answer as correct in case it clarified your doubt.
2

A less cryptic while loop that does the same thing would be:

var f = 1;
var i = 2;

++i;                // increment i
while (i < 5) {     // loop while i is less than 5
  f = f * i;        // assign f * i to f. aka "scale f by i"
  ++i;              // increment i
}

console.log("i:", i, "f:", f);

Here's a table

Iteration    |   i   |   f
------------------------------
Before loop  |   3   |   1
After 1st    |   4   |   3
After 2nd    |   5   |  12

And it exits after the 2nd iteration because 5 is not less than 5.

Comments

1

The while loop is executed every time when, the expression within the braces is truthy (https://developer.mozilla.org/en-US/docs/Glossary/Truthy). Hence when i is less then 5, an iteration is executed. But ++ before i might be tricky. Prefix is added before the execution, hence, this loop will be iterated with i=2+1=3 and i=3+1=4.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.