4.8 RangeError: maximum call stack size exceeded - Help Please!


#1

I keep getting the message "RangeError: Maximum call stack size exceeded" and I can't figure out how to fix it. Any help would be appreciated!

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random(); 
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2) {
    compare(userChoice, computerChoice);
    
if (choice1 === choice2) {
    return "The result is a tie!";
}
else if (choice1 === "rock") {
    if (choice2 === "scissors") {
        return "rock wins";
    }
    else {
        return "paper wins";
    }
}

else if (choice1 === "paper") {
    if (choice2 === "rock") {
        return "paper wins";
    }
    else {
        return "scissors win";
    }
}

else if (choice1 === "scissors") {
    if (choice2 === "rock") {
        return "rock wins";
    }
    else {
        return "scissors win";
    }
}
};

console.log(compare(userChoice, computerChoice))

#2

Hi try to remove the compare(userChoice, computerChoice); under
var compare = function(choice1, choice2)


#3

That worked, thank you so much!


#4
var compare = function(choice1, choice2) {
    compare(userChoice, computerChoice);

The explanation is that this is kind of an infinite loop with functions.
Think of it this way: Functions are sub-programs that are not run on their own but need to be called and when you call them you interrupt your work flow save the data and go on. So when your program is a sheet of paper with tasks on it then a function call would be an imaginary boss giving you a new sheet with higher priority. So you put your current paper on a stack and go on.

In your case you enter the function and the first step is to enter the function again and in this function the first step is to enter the function again and ... and so on. So your stack gets higher and higher and as you exceed the maximum capacity of functions being kept at rest before you actually work on one of them you get this error. Hope this helps.