Score calculation
- TypeScript course
- Intermediate
- Lesson 79/89
- 5 min
Write the score calculation logic.
Score calculation logic
Score calculation is the process of finding the number of correct answers. Each answer's result is collected in a boolean array; then the true values in this array are counted. A counter variable is incremented with a for...of loop to find the total.
function calculateScore(results: boolean[]): number {
let score = 0;
for (const r of results) {
if (r) score++;
}
return score;
}Counter increment
While calculating the score, the counter is incremented by one when a correct answer is found. The skor++ expression is used; this is the same as skor = skor + 1. At the end of the loop the counter value gives the total number of correct answers.
let score = 0;
if (correct) score++;
// same as score = score + 1Practice skorHesapla function
Define a skorHesapla function: (sonuclar: boolean[]): number. In its body, start skor at 0, loop over sonuclar with for...of; do skor++ on each true value and finally return skor. Print the result of calling skorHesapla([true, false, true]) with console.log.
Starter code
// skorHesapla fonksiyonu tanımla
// boolean[] alıp number dönsün
// for...of ile true'ları say
// skorHesapla([true, false, true]) yazdırSample solution
function skorHesapla(sonuclar: boolean[]): number {
let skor = 0;
for (const s of sonuclar) {
if (s) skor++;
}
return skor;
}
console.log(skorHesapla([true, false, true]));Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type of parameter does the score calculation function take?
- Soru[]
- string
- number
- boolean[] Correct answer
Explanation: Score calculation takes a boolean[] array containing the correct/wrong result of each question and returns a number.
2 Increment counter by one
let skor = 0;
if (dogru) skor____;
let skor = 0;
if (dogru) skor++;
Explanation: To increment a counter by one, the ++ increment operator is used; it is equivalent to skor = skor + 1.
3 Score calculation concepts
| Term | Meaning |
|---|---|
boolean[] |
Results array |
for...of |
Loop structure |
skor++ |
Counter increment |
number |
Return type |