Continuing the discussion from Review DOM Manipulation by Building a Rock, Paper, Scissors Game - Step 4:
i noticed i updated both player and computer text first before the roundresultsmsg and it didnt work,please someone explain why
Continuing the discussion from Review DOM Manipulation by Building a Rock, Paper, Scissors Game - Step 4:
i noticed i updated both player and computer text first before the roundresultsmsg and it didnt work,please someone explain why
If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.
The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.
Thank you.
Because the code relies on side effects.
Calling getRoundResults
not only returns a string for use in updating the DOM, it also increments the two top-level variables playerScore
and computerScore
(unless it is a tie, then it only returns a string).
function showResults(userOption) {
console.log('**** before getRoundResults function call **** \n');
console.log('playerScore', playerScore); // playerScore 0
console.log('computerScore', computerScore); // computerScore 0
roundResultsMsg.innerText = getRoundResults(userOption);
console.log('\n **** after getRoundResults function call **** \n');
console.log('playerScore', playerScore); // playerScore 1
console.log('computerScore', computerScore); // computerScore 0
playerScoreSpanElement.innerText = playerScore;
computerScoreSpanElement.innerText = computerScore;
};
showResults("Scissors");
Relying on side effects is one thing, but making a function that returns a string to use for DOM updates also change top-level variables as a side effect is questionable.
Your confusion about why the order matters also reflects this.
roundResultsMsg.innerText = getRoundResults(userOption);
This code in no way communicates that calling getRoundResults
will change some external dependency (i.e. the side effect of changing the top-level variables).
The fact that the code after the function call relies on the side effects, makes it even harder to reason about.