Search code examples
javascriptjavascript-objectsprompt

How do I add prompt entry to object and have it called back in another prompt?


I'm making a color guessing game. I'm trying to have a prompt ask for the players name, and then have the players first and last name pop up on the next prompt before the game starts.

function user() {
    let player = {
        firstName: '',
        lastName: ''
    }

    player = prompt("To play enter your first and last name:");
    if (player === null) {
        alert("This game is cancelled.");
        return;
    } else {
        player.name = prompt("Thank you, let get started " + player.name + "!");
        runGame();
    }
}

Solution

  • It seems that you're confusing variable names. You are assigning the result of the name to player variable, not player.name.

    function user() {
        let player = {
          // if we're reading the full name at once we should get rid of redundancy
          name: null
        }
    
        // here we assign the result of the prompt to name attribute of player object
        player.name = prompt("To play enter your first and last name:");
        // honestly I don't know what empty prompt returns so I would fall back to rejecting all falsey values
        if (!player.name) {
            alert("This game is cancelled.");
            return;
        } else {
            // Alert is definitely a better choice here as the player doesn't input any information
            alert("Thank you, let get started " + player.name + "!");
            runGame();
        }
    }