-2

I'm confused. Why does i+=1 in the following block of code print the output 12x, but i+=2 only prints it 6 times? Shouldn't it be the other way around? (My brain isn't working today.)

function printManyTimes(str) {
  "use strict";

  const SENTENCE = str + " is cool!";

  for (let i = 0; i < str.length; i += 2 ) {
    console.log(SENTENCE);
  }
}

printManyTimes("freeCodeCamp");
Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • Which set has more members `{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }` or `{2, 4, 6, 8, 10, 12}`? – VLAZ Oct 22 '19 at 16:28
  • Are you asking why it takes 12 times to get to a number with 1 while counting by 2 it takes 6 times??? – epascarello Oct 22 '19 at 16:32

4 Answers4

4

It loops while i is less than str.length.

If you increase i twice as quickly, then it becomes as long as str.length in half the time.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Because you are advancing the iterator two units per each iteration

jperelli
  • 6,988
  • 5
  • 50
  • 85
0

Here is a modified version of your code to show how a for loop works. Quentin's answer explains it pretty well.

function printManyTimes(str, amountToIncrement) {
  "use strict";

  const SENTENCE = str + " is cool!";

  for (let i = 0; i < str.length; i += amountToIncrement ) {
    console.log(SENTENCE + " " + i);
  }
}

console.log("increment amount as 1")
printManyTimes("freeCodeCamp", 1);

console.log("increment amount as 2")
printManyTimes("freeCodeCamp", 2);

console.log("increment amount as 3")
printManyTimes("freeCodeCamp", 3);

console.log("increment amount as .5")
printManyTimes("freeCodeCamp", .5);
joehinkle11
  • 491
  • 1
  • 4
  • 9
0
function printManyTimes(str) {
  "use strict";

  const SENTENCE = str + " is cool!"; // freeCodeCamp is cool!

  for (let i = 0; i < str.length; i += 2 ) { 
    // if i+=2 in your loop the console log run only while i = [0, 2, 4, 6, 8, 10] - 6 times
    // if i+=1/i++ in your loop the console log run only while i = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] - 12 times
    console.log(SENTENCE);
  }
}

printManyTimes("freeCodeCamp"); // freeCodeCamp length = 12

it's a basic knowledge of arrays. You can find more information in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for