Challenge 2: Functions
- TypeScript course
- Beginner
- Lesson 87/89
- 6 min
Build a calculation by writing type-safe functions.
Challenge 2: Functions
In this challenge you will write type-safe functions. You will write two functions with explicit parameter and return types: isEven, which checks whether a number is even, and grade, which converts a score to a letter grade.
Practice isEven function
Write a function isEven(n: number): boolean. Return true if n is even, false if odd. Print the results of isEven(4) and isEven(7).
Starter code
// isEven(n: number): boolean yaz
// çift ise true, tek ise false döndür
// iki çağrıyı yazdırSample solution
function isEven(n: number): boolean {
return n % 2 === 0;
}
console.log(isEven(4));
console.log(isEven(7));Expected output
true false
Practice grade function
Write a function grade(score: number): string. Return "A" for 90 and above, "B" for 80-89, "C" for 70-79, and "F" otherwise. Print the results of grade(95) and grade(65).
Starter code
// grade(score: number): string yaz
// 90+ A, 80+ B, 70+ C, diğer F
// iki çağrıyı yazdırSample solution
function grade(score: number): string {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
console.log(grade(95));
console.log(grade(65));Expected output
A F
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In the definition function isEven(n: number): boolean, what does : boolean specify?
- The function name
- The parameter type
- The error type
- The return type Correct answer
Explanation: The : boolean after the parameter is the return type. It guarantees the function returns a boolean value.
2 Complete the return type
function double(x: number): ____ { return x * 2; }
function double(x: number): number { return x * 2; }
Explanation: The double function returns a number, so the return type is number. string is text, void means no value, any removes type safety.
3 Function parts
| Term | Meaning |
|---|---|
(n: number): boolean |
Takes number, returns boolean |
n % 2 === 0 |
Even number check |
(score: number): string |
Takes number, returns string |
return "A" |
Returns a string value |