Answer check
- TypeScript course
- Intermediate
- Lesson 78/89
- 5 min
Write the answer validation function.
What is answer checking?
Answer checking is a function that determines whether the user's answer is correct. The question's dogruIndex is compared with the index chosen by the user. The result returns a boolean: true means correct, false means wrong.
function checkAnswer(correctIndex: number, answer: number): boolean {
return correctIndex === answer;
}Strict equality comparison
The === operator is used in answer checking. It compares both value and type; for example 0 === 0 is true but "0" === 0 is false. This prevents unexpected type conversions and makes the comparison safe.
Practice cevapKontrol function
Define a cevapKontrol function: (dogruIndex: number, cevap: number): boolean. Its body should return dogruIndex === cevap. Print the result of calling cevapKontrol(1, 1) with console.log.
Starter code
// cevapKontrol fonksiyonu tanımla
// iki parametre karsilastirip boolean donsun
// cevapKontrol(1, 1) cagrisini yazdirSample solution
function cevapKontrol(dogruIndex: number, cevap: number): boolean {
return dogruIndex === cevap;
}
console.log(cevapKontrol(1, 1));Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type does the cevapKontrol function return?
- boolean Correct answer
- void
- string
- number
Explanation: Answer checking returns a correct/wrong result, so it returns a boolean value.
2 Strict equality operator
function cevapKontrol(dogruIndex: number, cevap: number): boolean {
return dogruIndex ____ cevap;
}
function cevapKontrol(dogruIndex: number, cevap: number): boolean {
return dogruIndex === cevap;
}
Explanation: The === operator is used for type-safe comparison in answer checking; == may perform type conversion.
3 Answer checking concepts
| Term | Meaning |
|---|---|
dogruIndex |
Correct answer index |
cevap |
User's choice |
boolean |
Return type |
=== |
Strict equality |