Bitpath

Lesson 2 · Unit 03

Arrow functions and scope

Where a variable lives, and functions written as values

13 exercisesabout 3 min

What you practise

  • Arrow syntax, block scope, optional and default parameters, a function's type written down, a first closure

Try a question from this lesson

Pick one

The variable bonus is created inside the block of the if. Which line does the compiler reject?

TypeScript
let score = 80;
if (score > 50) {
  let bonus = 10;
  score = score + bonus;
}
console.log(score);
console.log(bonus);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Scope

The part of a program where a variable can be used is its scope. It runs from the line that creates the variable to the closing curly bracket of the block it is in.

Code inside a block can see variables from outside it. It does not work the other way round.

So a function's parameters and variables are private to it. Two functions can both have a total without clashing.

TypeScript
const rate = 2; // outside
function pay(hours: number): number {
  const total = hours * rate; // inside
  return total;
}
console.log(pay(5)); // 10

Concept

Arrow functions

A function can be written as a value and stored in a variable. The short way is an arrow function: the parameters, an arrow =>, then the body.

When the body is a single expression, leave out the curly brackets and the return: the expression is the result.

All three functions below do the same job, and are called the same way.

TypeScript
function double(n: number): number {
  return n * 2;
}
const twice = (n: number): number => {
  return n * 2;
};
const short = (n: number) => n * 2;
console.log(twice(2), short(2)); // 4 4

Concept

Optional parameters

A question mark after a parameter name makes it optional: a call may leave it out.

Inside the function, a parameter that was left out holds undefined, the value that means "nothing was given". Check for it before you use the parameter.

Optional parameters come last, after the ones every call must give.

TypeScript
function tag(msg: string, mark?: string) {
  if (mark === undefined) {
    return msg;
  }
  return mark + msg + mark;
}
console.log(tag("hi"));      // hi
console.log(tag("hi", "*")); // *hi*

9 more exercises in the app

  • 4× type the answer
  • 1× fill the blanks
  • 3× multiple choice
  • 1× match the pairs

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