Issue
I am learning javaScript and am trying to make a scoreboard counter. So far, my code looks pretty messy and DRY. Is there any way to combine the home and guest score functions into one function for each?
/*Scoring*/
let homeScore = 0
let guestScore = 0
const homeScoreCard = document.getElementById("home-score");
const guestScoreCard = document.getElementById("guest-score");
function increaseHomeScore(n) {
homeScoreCard.innerHTML = homeScore += n
}
function increaseGuestScore(n) {
guestScoreCard.innerHTML = guestScore += n
}
function threePoints() {
increaseHomeScore(3);
}
function twoPoints() {
increaseHomeScore(2);
}
function onePoint() {
increaseHomeScore(1);
}
function gThreePoints() {
increaseGuestScore(3);
}
function gTwoPoints() {
increaseGuestScore(2);
}
function gOnePoint() {
increaseGuestScore(1);
}
Solution
The function can take a parameter of how much to increase the score by:
function increaseHomeScore(n) {
homeScoreCard.innerHTML = homeScore += n
}
Then when you want to increase the home team score, you can call the function like this:
increaseHomeScore(2);
Answered By – John Koerner
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0