'Simplify Javascript Function
I have two functions that check for the correct answer:
If btnA clicked --> check if correct and continue quiz if btnB clicked --> check if correct and continue quiz
How can I simplify these two functions and make 1 function that checks answer depending on which button was clicked.
function cleanCheckAnswer() {
if(cleanBtn.value === questions[pos][3]) {
console.log('correct');
correct++;
pos++;
renderQuestion();
} else {
console.log ('incorrect');
pos++;
renderQuestion();
}
}
function uncleanCheckAnswer() {
if(uncleanBtn.value === questions[pos][3]) {
console.log('correct');
correct++;
pos++;
renderQuestion();
} else {
console.log('incorrect');
pos++;
renderQuestion();
}
}
Solution 1:[1]
How about:
function genericCheckAnswer(value) {
if(value === questions[pos][3]) {
console.log('correct');
correct++;
} else {
console.log('incorrect');
}
pos++;
renderQuestion();
}
function cleanCheckAnswer() {
genericCheckAnswer(cleanBtn.value)
}
function uncleanCheckAnswer() {
genericCheckAnswer(uncleanBtn.value)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Magnus J |
