'push() function is not adding to the end of array, is instead replacing index 0 with pushed object

I have a prompt asking a user for a number(guess), until they guess a randomly selected number(num). I'm trying to keep track of these guesses by putting them in an array.

 let guessesArray = [];

if (guess == num && guess != NaN) {
    guessesArray.push(guess);
    message.innerHTML = "You got it! It took you " + guessesArray.length +
        " tries and your guesses were " + guessesArray + ".";

}
else if (guess > num && guess != NaN) {
    if (guess <= max) {
        guessesArray.push(guess);
        message.innerHTML = "No, try a lower number.";

    } etc...

as i watch the console while guessing numbers, every time the push function is used, it just replaces the value at index 0. so when the user finds the correct answer, the message they receive is always that they got the answer in 1 guess and what should be a list of numbers that they guessed, is instead just the last number they guessed. How can I properly append to an array in JS?

function do_guess() {
    let guess = Number(document.getElementById("guess").value);
    let guessesArray = [];

    if (guess == num && guess != NaN) {
        guessesArray.push(guess);
        message.innerHTML = "You got it! It took you " + guessesArray.length +
            " tries and your guesses were " + guessesArray + ".";

    }
    else if (guess > num && guess != NaN) {
        if (guess <= max) {
            guessesArray.push(guess);
            message.innerHTML = "No, try a lower number.";

        }
        else {
            message.innerHTML = "That number is not in range, try again.";
        }
    }
    else if (guess < num && guess != NaN) {
        if (0 < guess) {
            guessesArray.push(guess);
            message.innerHTML = "No, try a higher number.";
        }
        else {
            message.innerHTML = "That number is not in range, try again.";
        }

    }
    else {
        message.innerHTML = "That is not a number!";
    }
    console.log(guessesArray);
}


Solution 1:[1]

Every time you call the do_guess method you're resetting guessesArray to an empty array (line 3). You need to define guessesArray outside of your method if you want it to retain the values you've pushed into it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thijs