For Loop: Counting the loop problem


#1

Hello!

My for loop isn't working quite the way I thought it would be.
I want my code to print out:

I'm counting and am on number 1
I'm counting and am on number 2
I'm counting and am on number 3
I'm counting and am on number 4
I'm counting and am on number 5

This is my code:
for (i = 0; i<5; i++) {
console.log("I'm counting and am on number " + i+1);
}

This is what I actually get:
I'm counting and am on number 01
I'm counting and am on number 11
I'm counting and am on number 21
I'm counting and am on number 31
I'm counting and am on number 41

How can I write the for loop to get the results I want?

Thanks!


#2

for (i = 0; i<5; i++) {
    console.log("I'm counting and am on number " + i+1);
}

Change i<5 to i<6 and change i = 0 to i = 1 and remove the +1 at the end of the console.log() statement.


#3

Oh, that totally makes sense!

Is there a way to add a number to the i variable?


#4

You're code should look like this:

for (i = 1; i < 6; i++) {
    console.log("I'm counting and am on number " + i);
}

#5

I guess what happens here:

console.log("I'm counting and am on number " + i+1);

is that because + has the same priority as + you just execute this from left to right meaning:

"I'm counting and am on number " + i

which concatenates the value of i to the string e.g. 0 for i=0. And then

"I'm counting and am on number0" + 1

again concatenating a number to a string.

Apart from what @jibblyj already suggested I'd try to increase the priority of the last addition like you'd do it in math with () around it:

 console.log("I'm counting and am on number " + (i+1));

according to this:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
you'd first compute the value and then to the concatenation.