Rockstar5645
Rockstar5645

Reputation: 4518

adding strings and numbers in javascript

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?

Upvotes: 0

Views: 88

Answers (1)

SLaks
SLaks

Reputation: 888203

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.

Upvotes: 4

Related Questions