Bitpath

Lesson 1 · Unit 03

Defining functions

Parameters, return values, and calls the compiler checks

13 exercisesabout 3 min

What you practise

  • function, typed parameters, the return type, void, return against console.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?

TypeScript
function greet() {
  console.log("Hello!");
}
greet();
greet();

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.

TypeScript
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.

TypeScript
function double(n: number): number {
  return n * 2;
}
const d = double(4);
console.log(d + 1); // 9

Concept

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.

TypeScript
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.

One email when Bitpath is ready to try. Nothing else. Privacy