Search code examples
javascriptfunctionscopeprompt

Beginner Question - Prompts , variables and scopes


I am trying to make a global scoped variable which stores a prompt value (player's name) but only fire when I click on the Start button.(This is why the variable is not declared outside the function Start)

How can I make this variable value (the name of the player) accessible to other functions, but only call the prompt when I click the start button?

 Game.start.onclick = function Start(){  
  let namePlayer1 = prompt("Hello Player 1 ! What is your name?");
  let namePlayer2 = prompt("Hello Player 2 ! What is your name?"); 

 return alert(namePlayer1 + "- You have the symbol 'X'.\n"+ namePlayer2 +
      "- You have the symbol 'O'.\nClick on the button Change Turn to start!")
 }

Solution

  • What @Jeremy and @Arthur mentioned in the comments could look like this. You should move only declaration of variables outside, not whole initialisation with prompt function call.

    let namePlayer1;
    let namePlayer2;
    
    Game.start.onclick = function Start() {
        namePlayer1 = prompt("Hello Player 1 ! What is your name?");
        namePlayer2 = prompt("Hello Player 2 ! What is your name?");
    
        return alert(
          namePlayer1 +
            "- You have the symbol 'X'.\n" +
            namePlayer2 +
            "- You have the symbol 'O'.\nClick on the button Change Turn to start!"
        );
    };