Lesson 2 · Unit 03
Arrow functions and scope
The short way to write a function, where a variable lives, defaults, and a first closure
What you practise
- Arrow syntax and when the braces go, block scope, default parameters, functions stored in variables, a first closure
Try a question from this lesson
Pick one
Here is another way to write a function: the parameter, an arrow, then the block, all stored in a variable. What do you think this prints?
const double = (n) => {
return n * 2;
};
console.log(double(6));Correct answer
12
Why
It works like the function you already know: n is the parameter, the block returns n * 2, and double(6) calls it. A function is a value like any other, so it can be stored under a const.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Arrow functions
An arrow function is written (parameters) => body and usually stored in a const.
If the body is a block in curly brackets, it needs its own return.
If the body is a single expression, leave out the curly brackets and the return: the value of the expression is returned for you.
const double = (n) => {
return n * 2;
};
const triple = (n) => n * 3;
console.log(double(5)); // 10
console.log(triple(5)); // 15Concept
Scope
A variable made with let or const exists only inside the curly brackets where it was created. That region is its scope.
Code inside a block can use names from outside it.
Code outside cannot use names from inside. When a function ends, its variables are gone.
const tax = 0.2; // outside
function withTax(price) {
const extra = price * tax; // inside
return price + extra;
}
console.log(withTax(10)); // 12
// extra does not exist out hereConcept
A function remembers
A function can use the variables around the place where it was created. It keeps that access for as long as it lives.
Here the inner arrow function is returned and called later. It still reaches count, although the outer function finished long ago.
This is called a closure.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 29 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 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.