Home > Software design >  Javascript getting a function to execute based on and/or
Javascript getting a function to execute based on and/or

Time:09-21

My code:

let buttonScore = document.querySelector('.button-score');
let paraScore = document.querySelector('.para-score');

buttonScore.addEventListener('click', scoreEntry);

function scoreEntry() {
    let scoreOne = Number(prompt('Enter first score'));
    let scoreTwo = Number(prompt('Enter second score'));
    
    if (scoreOne > scoreTwo) {
        scoreCheck();
    }
}

function scoreCheck() {
    if (scoreOne > 9) {
        paraScore.textContent = 'Excellent!';
    } else if (scoreOne < 7) {
        paraScore.textContent = 'Not enough';
    } else {
        paraScore.textContent = 'Good';
    }
}

Upon the user entering the two scores, I want the script to select the bigger score of the two and run scoreCheck() on it. I assume my problem has to do with non-global variables. In case this can also be done with one function instead of two, I'd also like to know please.

Would very much appreciate clarification, thanks in advance.

CodePudding user response:

You should make the variable a parameter to the second function.

Instead of testing whether one score is higher than the other, use Math.max() to select the higher score, and pass that as the argument.

function scoreEntry() {
    let scoreOne = Number(prompt('Enter first score'));
    let scoreTwo = Number(prompt('Enter second score'));
    
    scoreCheck(Math.max(scoreOne, scoreTwo));
}

function scoreCheck(score) {
    if (score > 9) {
        paraScore.textContent = 'Excellent!';
    } else if (score < 7) {
        paraScore.textContent = 'Not enough';
    } else {
        paraScore.textContent = 'Good';
    }
}
  • Related