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?

asked Jul 6, 2016 at 17:30
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

answered Jul 6, 2016 at 17:34
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.

answered Jul 6, 2016 at 17:36

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.

answered Jul 6, 2016 at 17:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.