A Shorter Way to Write Functions

JavaScript has a second, shorter way to write a function. It is called an arrow function, and you will see it everywhere in modern code:

const triple = n => n * 3;
console.log(triple(4));

Output:

12

An arrow function has parameters, then an arrow =>, then the result. You can read n => n * 3 as "n becomes n times 3". It does the same job as this function:

function triple(n) {
  return n * 3;
}
console.log(triple(4));

Output:

12

The short form has a few rules. They depend on how many parameters you have and how long the body is:

// Two or more parameters: use parentheses.
const add = (a, b) => a + b;

// No parameters: use empty parentheses.
const roll = () => "rolled!";

// More than one line: use braces and return.
const shout = text => {
  const loud = text.toUpperCase();
  return loud + "!";
};

console.log(add(2, 3));
console.log(roll());
console.log(shout("hello"));

Output:

5
rolled!
HELLO!

text.toUpperCase() gives a copy of the string in capital letters. You will see more string tools like it in the Strings section.

Look at the difference between the forms. When the body has no braces, the arrow function returns the value of the expression for you. When you add braces, you must write return yourself. If you add braces and forget return, the function returns undefined:

const triple = n => {
  n * 3;
};
console.log(triple(4));

Output:

undefined

This is the most common mistake with arrow functions.

Notice that each arrow function is stored in a const. An arrow function is a value, and const triple = ... gives that value a name. For everything in this course so far, const f = n => ... and function f(n) { ... } do the same job. A simple guide: use function for the main, named parts of your program, and use arrows for short functions, especially ones you pass into other functions. The Functions as Values lesson, later in this section, shows why.

There is one more difference, in how arrow functions treat the keyword this. It matters only when you get to the Classes section.

In the exercise, complete three short arrow functions.