1

I'm currently teaching myself JavaScript and I'm trying to get my loops down. I'm having an issue with += not working while ++ does. It's just something simple but I'm obviously not picking up on it right now. Sorry if this has been asked before, it seems like a simple fix but I just couldn't find it.

var providedNumber = prompt("Please enter a number:");

while (parseInt(providedNumber) <= 20 ) {
    document.write("<h3> Counting up " + providedNumber + "</h3>");

    providedNumber += 1;
} 

I know I have to parseInt() when inputting from a prompt to convert to an integer, do I also need to do that when I am adding or += 1? It works without it if I just use the ++?

  • "1" += 1 === "11" while "1"++ === 2 because it will parse to an int, increment, and then assign. It is because your provided number is stored as a string, and must first be converted in memory to a number. – Robert Mennell Mar 27 '19 at 03:44
  • providedNumber is string and when you use += it just pit the new number at the end of the string. But ++ would convert it to number and raise it by 1 – richard nelson Mar 27 '19 at 03:44
  • You can do `"

    " + +providedNumber + "

    "`
    – Jack Bashford Mar 27 '19 at 04:03

0 Answers0