Patrick
Patrick

Reputation: 17

beginner javascript for loop puzzle

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

Upvotes: 0

Views: 168

Answers (4)

Qudus Bashiru
Qudus Bashiru

Reputation: 11

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.

Upvotes: 0

Ele
Ele

Reputation: 33736

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; }

Upvotes: 1

Karl
Karl

Reputation: 1724

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);
}

Upvotes: 0

Jesse
Jesse

Reputation: 2084

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.

Upvotes: 3

Related Questions