← Back to course: JavaScript from scratch

Arrow functions, parameters and week 5 review

Video coming soon

Arrow functions are a shorter syntax for writing functions, introduced in ES6 and everywhere today. You have already seen them inside map, filter and reduce. In this lesson you learn all their forms and also default and rest parameters, which make your functions more flexible. At the end we review the whole week.

Arrow function syntax

They are written with parameters, an arrow => and a body. If the body is a single expression, you can omit the braces and the return: the value of the expression is returned automatically (implicit return). With a single parameter you can omit the parentheses, although many teams prefer to keep them. If you use braces, you must write an explicit return. To return an object literal with implicit return, wrap it in parentheses.

javascript
const add = (a, b) => a + b;            // implicit return
const square = (n) => n * n;
const greet = () => 'Hello';            // no parameters
const describe = (name, age) => {      // braces: explicit return
  const label = age >= 18 ? 'adult' : 'minor';
  return `${name} is ${label}`;
};
const makeUser = (name) => ({ name, active: true }); // object in parentheses

console.log(add(2, 3), square(5), greet()); // 5 25 Hello
console.log(describe('Ivo', 20));           // Ivo is adult
console.log(makeUser('Sam'));               // { name: 'Sam', active: true }

Arrow functions have an important difference from normal functions: they do not have their own this, they use the one from the place where they are defined. That makes them perfect for small functions and callbacks, but you should not use them as object methods that need this. We will see it with classes in week 6.

Default and rest parameters

A default parameter is used when the argument is not passed or is undefined. It is written with = in the definition. The rest parameter (three dots) collects all the leftover arguments in a real array, and it must be the last one. It is the modern way to accept a variable number of arguments, and it replaces the old arguments object. Note that the default value applies only with undefined: passing null or 0 does count as a value.

javascript
function welcome(name = 'guest', greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}
console.log(welcome());              // Hello, guest!
console.log(welcome('Ana'));         // Hello, Ana!
console.log(welcome(undefined, 'Hi')); // Hi, guest!

const sum = (...numbers) => numbers.reduce((acc, n) => acc + n, 0);
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum());           // 0

function logAll(first, ...rest) {
  console.log(first, rest);
}
logAll('a', 'b', 'c'); // a [ 'b', 'c' ]

const nums = [5, 8, 2];
console.log(Math.min(...nums)); // 2

Week 5 review

  • Functions group reusable code; return gives back a value and ends the function.
  • Functions are values: they are stored in variables and passed as arguments.
  • let and const have block scope; inner functions see outer variables.
  • A closure keeps the variables of the environment where the function was born.
  • Arrows shorten the syntax; default and rest parameters give flexibility.

Functions that return functions

By combining arrows and closures you can build specialized functions from a general one. This technique is called currying or partial application, and it consists of fixing some arguments in advance. For example, a function that receives a tax rate and returns another one that computes prices with that tax. The result is code that reads almost like a sentence and avoids repeating the same argument again and again. You do not need to master it today, but recognizing it will help you understand the code of other people and the libraries you will use in the future.

javascript
const withTax = (rate) => (price) => price * (1 + rate);

const spainPrice = withTax(0.21);
const reducedPrice = withTax(0.1);

console.log(spainPrice(100));   // 121
console.log(reducedPrice(100)); // 110
console.log([10, 20].map(spainPrice)); // [ 12.1, 24.2 ]

Test what you learned

Question 1 of 7

What does a function without return give back?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →