Arrow functions and callbacks
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
A shorter way to write functions
ES6 added arrow functions in 2015. They are a more compact way to write a function, and you will see them in almost all modern code.
Here is a normal function and its arrow version side by side:
function add(a, b) {
return a + b;
}
const addArrow = (a, b) => {
return a + b;
};
The arrow goes between the parameters and the body. Both do the same job.
Short forms
If the body is a single expression, drop the braces and the return. The value of the expression is returned automatically.
const add = (a, b) => a + b;
const double = n => n * 2; // one parameter: brackets optional
const sayHi = () => "Hi there"; // no parameters: empty brackets needed
console.log(add(2, 3)); // 5
console.log(double(7)); // 14
console.log(sayHi()); // Hi there
Careful when returning an object. The curly braces would look like a function body, so wrap the object in brackets:
const makeUser = (name) => ({ name: name, active: true });
console.log(makeUser("Sara")); // { name: 'Sara', active: true }
Without the extra brackets, JavaScript thinks the braces mark the body and the function returns undefined.
I use the short form for tiny one-line helpers and the braces form when the function needs more than one step.
What is a callback?
A callback is a function that you pass to another function, so that it can be called later. We saw this with applyTwice. Arrow functions make callbacks short and readable.
function repeat(times, action) {
for (let i = 0; i < times; i++) {
action(i);
}
}
repeat(3, i => console.log("Step " + i));
repeat takes a number and a function. For every round, it calls action and passes the round number. We give it an arrow function written right where we call it. We do not need to give that function a name.
Timers use callbacks too. This one runs after one second:
setTimeout(() => {
console.log("One second later");
}, 1000);
console.log("This prints first");
The second line prints first. setTimeout hands the callback to the runtime and moves on. When the time is up, the runtime calls your function. Understanding this "run later" idea is the key to async code, which we cover in the follow-up course.
Arrow functions and this
There is one real difference between arrow and normal functions. They treat the special keyword this differently. A normal function gets its own this, which depends on how it is called. An arrow function does not have its own this. It uses the this from the place where it was written.
For now, you only need a rule of thumb. Use arrow functions for callbacks and small helpers. Use normal functions or method syntax when you define methods on an object:
const counter = {
count: 0,
increment() {
this.count++;
},
};
counter.increment();
console.log(counter.count); // 1
If we had written increment: () => { this.count++ }, it would not work, because the arrow function would not see counter as this. We will study this properly in the next course.
Immediately useful: arrows with arrays
Arrow functions shine with array methods, which come up in two lessons:
const prices = [100, 250, 80];
const withTax = prices.map(p => p * 1.17);
console.log(withTax); // [117, 292.5, 93.6]
Compare this with a loop. The arrow version says what we want, and not how to do it step by step.
Common mistakes
- Forgetting the brackets around an object literal. The function returns
undefined. - Using an arrow function as an object method.
thiswill not be the object. - Writing a return inside the short form.
n => return n * 2is a syntax error. Either use braces withreturnor dropreturn. - Cramming too much into one line. If an arrow function needs a comment to explain it, give it a name and a proper body.
- Calling the callback by accident.
setTimeout(doWork(), 1000)runsdoWorkimmediately and passes its result. WritesetTimeout(doWork, 1000).
Try it yourself
- Rewrite
function square(n) { return n * n; }as an arrow function in the shortest form. - Write an arrow function
isAdult(age)that returns true for 18 and over. - Call
repeat(4, i => ...)from this lesson so that it prints the squares of 0 to 3. - Use
setTimeoutto print "A", "B", "C" at one, two and three seconds. Guess the order first, and then check.
const add = (a, b) => a + b;
const double = n => n * 2; // one parameter: brackets optional
const sayHi = () => "Hi there"; // no parameters: empty brackets needed
console.log(add(2, 3)); // 5
console.log(double(7)); // 14
console.log(sayHi()); // Hi there
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account