Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm learning JavaScript, and I came across a problem.
I wanted to see the loop until infinity for 2*2. I've initialized two variable x and y. I wrote a while loop ( while(x != Infinity){} ).

It's working when write like this:
(y = y + x + "<br>";).
But not when I wrote like this:
(y = "" + x + "<br>";).

I couldn't understand the difference. It seems like both the lines are same. Can someone please help me understand the concept?

Thank you:)

What I have tried:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

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

</body>
</html>
Posted
Updated 18-Dec-17 19:34pm

1 solution

if you see this line
y = "" + x + "<br>"

you are keep on overwriting the variable y from 0 to Infinity so at the end of the loop the last value will be stored to the variable which is Infinity
You should append the value to variable to see the entire loop result.
use
y += x + "<br>"
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900