Write Arrow Functions

Priya’s game night page lists this month’s games and who’s coming, but only Priya can change it by editing main.js. In this course, her guests get to use it. They’ll click a button to say they’re bringing a game, vote on what to play first, and filter the list down to quick games.

Every one of those clicks works the same way. Your script hands the browser a function, and the browser calls it when the click happens. In this lesson, you’ll learn to write a function as a value you can store and hand over, in the compact form called an arrow function. Start with a function you could already write.

Store a Function in a Constant

To hand the browser a function, you first need to treat a function as a value, the way you treat a string or a number. You’ll see what that means with a function Priya’s page needs.

This course picks up Priya’s page as you’d have it after building it: index.html, style.css, and main.js in a scratch folder, served by a local server such as VS Code’s Live Preview. If you’re starting here, you need the JavaScript basics, including functions with return and constants. You can follow the first two parts of this lesson in any Chrome or Edge tab. The last part gives you a short starter to type, so you can work in the same tab too.

Text lessons like this one are for typing along. Videos show what moves, an exercise closes each section, and the course ends with a project, Priya’s RSVP board. For now, open a new tab, go to about:blank, and open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS. A blank tab keeps these experiments apart from Priya’s page until her script is ready for them.

Priya’s drawGames() builds each game’s line, like Catan: 3-4 players, 90 minutes, inside its loop. Later in the course, the game cards need that same text, so it deserves a function of its own. As a function declaration, the kind you already know, it would look like this:

Language: JavaScript
function describeGame(game) {
  return game.name + ": " + game.minPlayers + "-" +
    game.maxPlayers + " players, " + game.minutes +
    " minutes";
}

If a function is a value, you can also write it where a value goes, on the right of =. Give the Console one game to work with, then the function written that way, pressing Shift+Enter between its lines:

Language: JavaScript
> const catan = { name: "Catan", minutes: 90,
…   minPlayers: 3, maxPlayers: 4 };
undefined
> const describeGame = function (game) {
…   return game.name + ": " + game.minPlayers + "-" +
…     game.maxPlayers + " players, " + game.minutes +
…     " minutes";
… };
undefined
> describeGame(catan)
'Catan: 3-4 players, 90 minutes'

This is a function expression: a function written as a value. It has no name of its own after the word function, and the const gives it one. You call it exactly as you’d call a function defined with a declaration.

Now enter the name on its own, without the parentheses after it:

Language: JavaScript
> describeGame
ƒ (game) {
  return game.name + ": " + game.minPlayers + "-" +
    game.maxPlayers + " players, " + game.minutes +
    " minutes";
}

This time, no line was built, because nothing called the function. Instead, the Console echoed the function itself, marked with ƒ. The constant describeGame holds a value, and that value is a function. The parentheses are what call it. Because the name holds the function without calling it, you can hand it to the browser later.

Shorten It to an Arrow

You’ll write a lot of small functions in this course, one for each kind of click, so a shorter form pays off. An arrow function drops the word function and puts => between the parameters and the body.

The Console remembers what you typed, newest first, so press Up until the const describeGame = function (game) { definition comes back. That’s three presses, because the first two bring back describeGame and describeGame(catan). Then change its first line:

Language: JavaScript
> const describeGame = (game) => {
…   return game.name + ": " + game.minPlayers + "-" +
…     game.maxPlayers + " players, " + game.minutes +
…     " minutes";
… };
undefined
> describeGame(catan)
'Catan: 3-4 players, 90 minutes'

Read (game) => { ... } as “take a game and do this.” The Console accepts a second const describeGame because it lets you replace a constant from an earlier line, which saves you from renaming it while you experiment. A script file doesn’t allow that.

This body has braces and a return, like any function you’ve written. When the whole body is one expression, an arrow function can be shorter. Delete the braces and the word return, and the expression’s value becomes the result:

Language: JavaScript
> const describeGame = (game) => game.name + ": " +
…   game.minPlayers + "-" + game.maxPlayers +
…   " players, " + game.minutes + " minutes";
undefined
> describeGame(catan)
'Catan: 3-4 players, 90 minutes'

This form is a concise body. With braces, the body can hold several statements, and only return hands a value back. Without braces, the body is one expression, and the arrow returns it for you. Choose the concise body when the function is one expression, as describeGame() is.

Arrows take any number of parameters, in the parentheses before =>. Guests will vote soon, so Priya needs a record of each vote: which game and who voted. That’s two parameters, and the result is an object:

Language: JavaScript
> const makeVote = (gameId, voter) =>
…   ({ gameId: gameId, voter: voter });
undefined
> makeVote("catan", "Amara")
{gameId: 'catan', voter: 'Amara'}

Watch out for the parentheses around the object. After =>, a { always starts a braced body. Without the parentheses, makeVote() returns undefined for one property and stops with a SyntaxError for two.

If you’d like to check that you can predict these results, the button below asks the mentor, RealJS’s AI tutor, for small arrows to read. Expect one at a time, with feedback on your answer before the next:

An arrow with no parameters keeps its empty parentheses. Its job is often to do something rather than to return something, like the functions a click will call:

Language: JavaScript
> const announce = () => console.log("Voting is open!");
undefined
> announce()
Voting is open!
undefined

The Console prints the message, then echoes undefined, the call’s result, because console.log() doesn’t return anything. With exactly one parameter, JavaScript’s arrow syntax also lets you leave out the parentheses, as in game => game.name. You’ll see that in other people’s code, but this course always writes them.

Move the Helpers Into main.js

Functions you typed in the Console vanish on the next reload, so Priya’s helpers belong in her script. If you have Priya’s files, open scratch/main.js. If you don’t, read along. A starter after the changes lets you try them in your blank tab. Here’s the drawGames() you’ll change, with its text built inside the loop:

Language: JavaScript
function drawGames() {
  gameList.replaceChildren();
  for (const game of games) {
    const item = document.createElement("li");
    item.textContent = game.name + ": " + game.minPlayers +
      "-" + game.maxPlayers + " players, " +
      game.minutes + " minutes";
    if (game.minutes > 60) {
      item.classList.add("long");
    }
    gameList.append(item);
  }
}

Add the two arrows below the games array and the line that finds gameList, above function drawGames(). Then have the loop ask describeGame() for each item’s text:

Language: JavaScript Filename: scratch/main.js
const describeGame = (game) => game.name + ": " +
  game.minPlayers + "-" + game.maxPlayers +
  " players, " + game.minutes + " minutes";

const makeVote = (gameId, voter) =>
  ({ gameId: gameId, voter: voter });

function drawGames() {
  gameList.replaceChildren();
  for (const game of games) {
    const item = document.createElement("li");
    item.textContent = describeGame(game);
    if (game.minutes > 60) {
      item.classList.add("long");
    }
    gameList.append(item);
  }
}

Save, and the page looks exactly as it did, with five games and Catan in bold. That’s the result you want, because the same text now comes from one place. You can confirm it. Change " minutes" in describeGame() to " min", save, and all five lines change. Then change it back. makeVote() waits for the votes later in this section.

If you joined the course here and don’t have Priya’s files, you can see the same game descriptions in your about:blank tab, with Catan in plain text because there’s no stylesheet. describeGame() and makeVote() are already there from the earlier parts of this lesson, so you still need a games list on the page and the games to fill it.

Type this starter into the Console one entry at a time, pressing Shift+Enter between the lines of the games array. It makes an empty list, adds it to the blank page, and keeps it in gameList, as Priya’s script does with her page’s list:

Language: JavaScript
> const games = [
…   { name: "Catan", minutes: 90,
…     minPlayers: 3, maxPlayers: 4 },
…   { name: "Ticket to Ride", minutes: 60,
…     minPlayers: 2, maxPlayers: 5 },
…   { name: "Codenames", minutes: 15,
…     minPlayers: 4, maxPlayers: 8 },
…   { name: "Carcassonne", minutes: 45,
…     minPlayers: 2, maxPlayers: 5 },
…   { name: "Azul", minutes: 40,
…     minPlayers: 2, maxPlayers: 4 },
… ];
undefined
> const gameList = document.createElement("ul");
undefined
> document.querySelector("body").append(gameList);
undefined

Then enter the new drawGames(), the one that asks describeGame() for each line, and call it:

Language: JavaScript
> function drawGames() {
…   gameList.replaceChildren();
…   for (const game of games) {
…     const item = document.createElement("li");
…     item.textContent = describeGame(game);
…     if (game.minutes > 60) {
…       item.classList.add("long");
…     }
…     gameList.append(item);
…   }
… }
undefined
> drawGames()
undefined

The undefined is the call’s result, because drawGames() doesn’t return anything. Its work shows on the page, where the blank tab now lists the five games, from Catan: 3-4 players, 90 minutes to Azul: 2-4 players, 40 minutes. Catan carries the long class, but it isn’t bold here, because a blank tab has no stylesheet.

The same check works here with two entries. Enter the describeGame definition again with " min" in place of " minutes", then call drawGames() to redraw the list:

Language: JavaScript
> const describeGame = (game) => game.name + ": " +
…   game.minPlayers + "-" + game.maxPlayers +
…   " players, " + game.minutes + " min";
undefined
> drawGames()
undefined

All five lines on the page now end in min. To change it back, press Up twice to bring back the describeGame definition, change " min" back to " minutes", press Enter, and call drawGames() again.

The next two watch-outs are about Priya’s script file, so they apply once you’re working in main.js.

Watch out for where the arrows go. If describeGame sits below the drawGames(); call, the Console shows Uncaught ReferenceError: Cannot access 'describeGame' before initialization. A constant can’t be used before its line has run, even when it holds a function. If you define a function with a declaration, as with drawGames(), you can call it from above its declaration.

You may also try calling describeGame(catan) in the page’s own Console and get a ReferenceError. A module keeps its names to itself, so the Console can’t reach them. That’s all you need about modules for now.

If you have function declarations of your own, rewriting a few is good practice. The button below asks the mentor to give you one to rewrite and check your version:

Priya’s script now holds two arrows in constants: describeGame(), which builds a game’s line, and makeVote(), which makes a vote record. So far, each one works only with what you pass in. To count votes, a function will have to change something outside itself, and the next video, Change Outer Variables Carefully, shows what happens when it does.

Become a Member to join the conversation.