typescript · level 1 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
hands the answer back so you can keep it.
So far your functions show things. Showing puts a value on the screen, and then it is gone. Your program cannot catch it, keep it or do maths with it.
To return a value, write return and the value. The call then turns into the answer, as if double(4) were the number 8. Add a after the brackets, like : number.
A function that hands nothing back has the return type , which means empty. Catch its answer anyway and you get undefined.
function double(n: number): number {
return n * 2;
}
let answer: number = double(4);
console.log(answer);
console.log(double(answer)); Showing is telling someone your answer, and return is handing it to them.
guess first
This one only shows. What will it print?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function double(n: number): void {
console.log(n * 2);
}
let answer = double(4);
console.log(answer);
your turn
Your turn. Build a dog years machine.
In the first blank, type how many dog years each year counts as. People often say 7. In the second, type your dog's age, real or made up. Then run it.
fix it
Your bonus never arrives. Can you fix it?
- Read the error:
TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.Phew! - In plain words: the label promises a number back, but nothing is ever returned.
- Put return in front of points * 2 on line 2, then press run.
nailed it
your functions can hand back answers. :D
console.logshows a value.returnhands it back to use.- The return type after the brackets says what comes back.
voidmeans a function hands nothing back.
new words in your collection
- return
- return type
- void
This lesson isn’t saved. A free account remembers every lesson you finish.