General for loop question


#1

Hi there.
I feel that I understand the basics of for loops, but there is something I'm not grasping. In the following code to compute 2 to the 10th power...

var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1);
result = result * 2;
console.log(result);

the result is 1024

What I don't understand is how the "result" variable is being plugged into the loop?? There are lots of instructions for the "counter" variable, but "result" seems to be pulled out of nowhere....


#2

Hi :slightly_smiling:

So, I'll break it fown for you. First, you declare your variable:

var result = 1; /* This sets result equal to 1 */

Second, you build your for loop:

for (thisVariable = thisNumber; run loop while this condition is true; every time you run through this loop, add this much to thisVariable) {
/* run this code */
}

Now, inside your loop, you have:

result = result * 2; /* this takes the var result and redefines it to equal itself times two */

Now that our variable has been redefined, your next line logs it:

console.log(result);

So, basically, your code takes your var result and multiples it by 2 for as long as counter < 10. Does this make sense or help in any way?


#3

As @quobogeba says, so long as counter is less than ten, it multiplies result by 2, stores it back in result, then adds 1 to counter.

var result = 1; /*So right here result is 1*/
for (var counter = 0; counter < 10; counter++) { /*++ is short for += 1, which is short for = counter + 1*/
    result = result * 2; //each time that counter is less than 10, it does this, increments counter by one, and checks again
}
console.log(result)

#4

All that makes sense to me.
Let me ask this, in the example I've included, would this be the same code?

var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1) {
result = result * 2;
}
console.log(result);

Did the example I'm working from simply omit the curly brackets by choice? Or are they not used in this instance? I feel like that may be where I'm being thrown off...


#5

Yes, simply a choice, but a bad one in my opinion, as it's harder to read that way.


#6

Ahhh, Ok. Without the braces, it seemed like the "result" variable was OUTSIDE the loop, which is why I couldn't see how it was getting included. Thank you so much for the help.


#7

No problem, that's what we're here for