Why does the browser crash?


#1

This is my code with I want to list every number that isn't equal 5 until one of them equals to 5.


var valtozo = Math.floor(Math.random() * 6);
while (valtozo != 5) {
    console.log(valtozo);
   valtozo;
}


#2

Let's run along your code.

var valtozo = Math.floor(Math.random() * 6);
Here you define valtozo. Let's say the result is 3

while (valtozo != 5) {
As long as valtozo is NOT 5...

console.log(valtozo);
... it logs valtozo into the console.

valtozo;
Here I assume you are trying to define valtozo again, with a new number. However, valtozo is a variable, not a function. Valtozo doesn't change - so the while loop will run forever (unless the starting number was 5).

To solve this, try putting valtozo = Math.floor(Math.random() * 6); into a function, and calling that function inside the while loop. However, make sure that valtozo is on a global scope, or else your code won't work.

You can do that by removing the var before valtozo when defining it inside the function.


#3

I've thought valtozo always changes because it based on an actual random number.


#4

Yes, valtozo can have 6 random values - 0, 1, 2, 3, 4 or 5. However, you are only defining valtozo once, so if valtozo is any number other than 5, it will stay like that until it's defined again. Like I said before, using valtozo; in your while loops doesn't redefine it - variables are not functions. In order to be able to redefine valtozo, you should make a function in which valtozo is defined, and run that function in the while loop.

I made this as an example of what your code should look like:

function randomizeNumber() {
   number = Math.floor(Math.random() * 10);
}
randomizeNumber();
while(number != 8) {
   console.log(number);
   randomizeNumber();
}

Remember to run your function once so valtozo is defined before starting the while loop.


#5

This works. But idk why must I call function before AND inside while loop.


#6

Since the function doesn't call itself, the function must be called once so that valtozo is defined. If it isn't, valtozo will be undefined, and the first thing console.log(number); logs, is 'undefined'. Inside the while loop, you should keep repeating the function so that you get a different number every time it loops.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.