Lesson 1 · Unit 03
Defining functions
Parameters, return values, and calls the compiler checks
What you practise
function, typed parameters, the return type,void,returnagainstconsole.log, a call with the wrong argument rejected
Try a question from this lesson
Pick one
The first three lines give a block of code a name. The last two lines use that name. What do you think this prints?
function greet() {
console.log("Hello!");
}
greet();
greet();Correct answer
Hello! twice
Why
Lines 1 to 3 define a function: they store the block under the name greet and run nothing. greet(); is a call: it runs the block. Two calls, two greetings. Write the code once, use it as often as you like.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Parameters
A function can take input. In its brackets you list parameters: variables that get their values from the call. Each parameter needs a type.
The values you put in the brackets of a call are the arguments. Here "Ada" is the argument and name is the parameter that receives it.
Same function, different argument, different result.
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
greet("Ada"); // Hello, Ada!
greet("Bo"); // Hello, Bo!Concept
return
return hands a value back to the place where the function was called. The call itself becomes that value, so you can store it or use it in an expression.
The type after the brackets, here : number, is the return type: what the function promises to hand back.
Printing shows a value to a person. Returning gives it to the rest of the program.
function double(n: number): number {
return n * 2;
}
const d = double(4);
console.log(d + 1); // 9Concept
void
A function that hands nothing back has the return type void. It is called for what it does, such as printing, not for a value.
If a function promises a value, as in : number, the compiler checks that it really returns one of that type.
Rule of thumb: functions that calculate should return. Leave the printing to whoever called them.
function show(msg: string): void {
console.log(msg);
}
function twice(n: number): number {
return n * 2;
}
show(`Twice 4 is ${twice(4)}`);9 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.