0

I'm new at javascript was wondering why I got four return values:

for(i=0; i < 10; i++) {
    i = i * i;
    console.log(i);
}
// 0
// 1
// 4
// 25
4
  • You changed the value of i upon assignment, therefore shortening the loop. Commented Mar 14, 2018 at 1:42
  • 1
    Quick note: You're logging 4 values to the console, not getting 4 return values. There's an important distinction there: a return value is a value returned from a function call. Commented Mar 14, 2018 at 1:56
  • 1
    What did you expect? Commented Mar 14, 2018 at 1:58
  • I suppose I expected more iterations, but now that it was explained the answer was pretty obvious. Commented Mar 14, 2018 at 3:41

4 Answers 4

3

Because you are setting the value of i inside your loop.

Initially i = 0; Prints 0x0 = 0; i = 0

Next iteration i = 1; Print 1x1 = 1; i = 1

Next iteration i = 2; Print 2x2 = 4; i = 4

Next iteration i = 5; Print 5x5 = 25; i = 25

i is now greater than 10 and therefore loop exit condition is met.

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

1 Comment

That's what I suspected while I was away from the computer and giving it some thought. Thanks for clearing that up!
1

Execute this snippet to get a little explanation:

var iterations = ['First', 'Second', 'Third', 'Fourth']
var j = 0;
for (i = 0; i < 10; i++) {
  var iteration = iterations[j++];
    console.log(`${iteration} iteration with i = ${i} and multiplying ${i} x ${i} =`, i * i);
  i = i * i;

}
console.log(`The for-loop ends because i = ${i} > 10`);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

There is an error in the logic of your loop. Since the loop sets the value of i to the product of itself i is repeatedly increasing with each iteration of the loop:

i = i * i;

It makes i greater then 10 (in your example 25) and terminates the loop. If you created some variable, say j as what is set to the product of i * i, it would loop 10 times. Something like this:

for(i=0; i < 10; i++) {
    var j = i * i;
    console.log(j);
}

Comments

0

The loop breaks because of the prior condition you set in your for statement; "i < 10". By assigning a new value to i in "i = i * i" overrides the incremental value "i++" you provided the for loop. To correct this, assign the value from product of "i * i" to a different variable name such as "s = i * i" and you can get your loop to complete without any break.

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.