0

I just have a question about some while loop logic. So, when you write a loop that displays a string of numbers to a document and say that while the loop is <= (less than or equal to) say, 5, and you tell the loop to add 1 each time this is true, wouldn't that mean that: while the loop is equal to 5 that it would add one to 5 too? It doesn't, but I messed up on some code when I was practicing and noticed that when it is equal to five it does not add one, but I thought it would...

console.log('2nd Loop:');
text = '';

// loop:
i = 1; 
while (i <= 5) {
  text += i + ' ';
  i += 1
}

console.log(text); // Should print `1 2 3 4 5 `.

1
  • It does work for me. Could you elaborate on what is the output you are getting. Could you explain what is not working for you? Commented Aug 17, 2017 at 16:13

4 Answers 4

2

the reason your text doesn't display a 6 isn't because i isn't incremented. It's because the text gets added onto before it's incremented.

In other words when executing on that 5th loop, the text would add on 5, and then it would increment i, and then it would check the loop again, which would no longer be valid and therefore 6 is never printed.

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

Comments

0

In memory, it adds one. It doesn't add it to the text though.

Since you're incrementing the value after assigning it and then the loop condition fails, it doesn't get to the part where you concatenate the string.

Comments

0

It does. Just output i and you'll see it's 6. text never gets the 6 because of when you increment i.

console.log('2nd Loop:');
text = '';

// loop:
i = 1; 
while (i <= 5) {
  text += i + ' ';
  i += 1
}

console.log(text,i); // Should print `1 2 3 4 5 `.

1 Comment

@hannacreed You don't see 6 in the snippet above? What browser are you using?
0

b/c you +1 after you add i to text, all you need to do is switch the two line order.

EDIT if you want it start with one just change your i to 0 to start with.

i = 1 

    console.log('2nd Loop:');

    text = '';

    i = 0; 
    while (i <= 5) {
      i += 1
      text += i + ' ';
    }

    console.log(text);

1 Comment

that would cause it to start printing out at 2 though.

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.