gilbert-v
gilbert-v

Reputation: 1305

Javascript: Function within a function

Is there any reason why this code isn't working? I have put the entire script into a function for the sake of the playAgain variable (see bottom) which would restart the function. Any help would be much appreciated.

function headsTails() {
    var userChoice;
    userChoice = prompt('Heads or Tails');

    function myGame(heads,tails) {  
        var result;
        var coin;
        result = Math.random()
        if(result > 0.5) {
            coin = "heads";
        } else {
            coin = "tails";
        }
        if(userChoice === "heads") {
            if(coin = "heads") {
                alert("You win!");
            } else if(coin = "tails") {
                alert("You lose!");
            }
        }
        if(userChoice === "tails") {
            if(coin = "heads") {
                alert("You lose!");
            } else if(coin = "tails") {
                alert("You win!");
            }
        }
    }
    myGame();
    var playAgain;
    playAgain = confirm(Do you want to play again?)
    if(playAgain) {
        headsTails();
    } else {
        alert("Thanks for playing!")
    }
}

Upvotes: 0

Views: 91

Answers (1)

JohnJohnGa
JohnJohnGa

Reputation: 15685

You have many syntax errors:

coin = "heads" -> coin === "heads"
coin = "tails" -> coin === "tails"
confirm(Do you want to play again ?) -> confirm("Do you want to play again ?")

I would recommend reading about Javascript and in general about programming languages...

Corrected headsTails function:

function headsTails() {
    var userChoice;
    userChoice = prompt('Heads or Tails');

    function myGame(heads, tails) {
        var result;
        var coin;
        result = Math.random();
        if (result > 0.5) {
            coin = "heads";
        } else {
            coin = "tails";
        }
        if (userChoice === "heads") {
            if (coin === "heads") {
                alert("You win!");
            } else if (coin === "tails") {
                alert("You lose!");
            }
        }
        if (userChoice === "tails") {
            if (coin === "heads") {
                alert("You lose!");
            } else if (coin === "tails") {
                alert("You win!");
            }
        }
    }

    myGame();
    var playAgain;
    playAgain = confirm("Do you want to play again ?")
    if (playAgain) {
        headsTails();
    } else {
        alert("Thanks for playing!")
    }
}

Upvotes: 1

Related Questions