0

The script below is an example I came across in a tutorial. It's supposed to show what happens to a number when it gets too big.

<script>
function myFunction() {
    var myNumber = 2; 
    var txt = "";
    while (myNumber != Infinity) {
        myNumber = myNumber * myNumber;
        txt = txt + myNumber + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

And here is the output:

4
16
256
65536
4294967296
18446744073709552000
3.402823669209385e+38
1.157920892373162e+77
1.3407807929942597e+154
Infinity

My two questions are basically

1) In the second iteration of the while loop, txt already has a character 4 in it (because a string plus a number is a string in Javascript) and then we add 16 to that string. Shouldn't we get 416 and so on?

2) Why does the break (br) element need to have a quotation marks around it?

2
  • 1
    1) At 2nd iteration, your txt becomes 4<br>16<br>, so its not 416 Commented Jun 30, 2015 at 19:06
  • txt = txt + myNumber + <br> would be variable = variable + variable + variable and <br> is not a variable. Commented Jun 30, 2015 at 19:06

1 Answer 1

4

1) No. In the second iteration, txt is "4<br>". Adding 16 results in "4<br>16"

2) That's a string literal like any other string literal.

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

1 Comment

@Rockstar5645 you are getting 416. You are just putting a <br> in between them like SLaks said. Thus there is a hard return between the two numbers. Add console.log(txt) inside the loop and you'll better see the numbers being added together.

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.