nc14
nc14

Reputation: 559

How to use output of prompt as global variable in another function

Following Odin Project Rock Paper Scissors - trying to use a JS prompt input in another function to work out who won a game.

Have stripped a lot out to hopefully make the question/answer as reusable as possible for others.

I have 2 global variables set :

let computerSelection;
let playerSelection;

I have a function (playRound) which works out the outcome of a round (who won) which I know works when hard coding the player selection (as I've tried console logging the output successfully).

However I want to replace the hard coding of the player selection to use the input of a prompt. But when I do this, it isn't setting the playerSelection properly as I'm just getting 'undefined' when I console log playRound().

My prompt :

function showModal() {
    selection = window.prompt('Rock, paper or scissors?').toLowerCase(); 
    playerSelection=selection
}

I know this works when I console log the playerSelection with a different button like this:

function print() {
    console.log(playerSelection);
}

however, when I try use it in my playRound() function it is showing undefined?

function playRound(playerSelection, computerSelection) {
  computerSelection = computerPlay();
  playerSelection = showModal(playerSelection); 

I've also tried just using

playerSelection = playerSelection

and also

playerSelection = showModal()

as I thought surely the global variable is set once the modal is complete but that is also returning undefined???

I don't understand why this isn't working in the playRound function as it seems the modal/prompt is setting the playerSelection variable (when I console.log playerSelection after doing it (using my test print() function?)

Upvotes: 0

Views: 606

Answers (2)

Siernam
Siernam

Reputation: 1

working on this myself I did let playerSelection = prompt(text)

Upvotes: 0

about14sheep
about14sheep

Reputation: 2009

You have an issue with scope here. Because you have a parameter called playerSelection being passed into the function it is setting that variable and not your global variable. You can solve this like this:

let playerSelection;
let computerSelection;

function playRound() {
  computerSelection = computerPlay();
  playerSelection = showModal(playerSelection);
}

function showModal() {
    return window.prompt('Rock, paper or scissors?').toLowerCase(); 
}

playRound();

Note that also you need to return the prompt result from showModal, a function without a return statement will always return undefined.

Upvotes: 1

Related Questions