Store Functions in Variables

Tomás is hosting movie night, and his friends keep a shared watchlist of films. Each film’s record includes a title, a running time, a genre, a list of people who’ve seen it, and a vote count. By the end of this course, you’ll build Tomás a picker that drops films that run too long, finds the ones nobody has seen, and prints a shortlist sorted by votes.

You could write that picker with the loops, arrays, and objects you already know. This course shows you a shorter and more flexible way, built on the fact that in JavaScript, a function is a value, like a number or a string. In this lesson, you’ll see that for yourself in Node’s REPL, then write Tomás’s first helpers as arrow functions stored in const variables. Start with one question. What is a function when you don’t call it?

Treat a Function Like Any Other Value

So far, you’ve used a function’s name with parentheses after it to call the function. That hides what the name holds on its own. A short experiment in the REPL shows you.

The REPL, short for Read-Eval-Print Loop, runs one line of JavaScript at a time and prints its value at once. To open it, type node in your terminal with nothing after it and press Enter. A > prompt appears. Type .exit whenever you want to leave.

This course uses the REPL for quick looks behind the scenes, and script files, run with node, for programs. Along the way, you’ll also watch short videos and finish each section with an exercise that checks your code.

Type each line of this session yourself. It stores a helper in a const variable, the way you’d store a number or a string. The helper turns a running time into a label. The session then logs the stored function, puts it in an array, and calls it from there:

Language: JavaScript
> const formatRuntime = function (minutes) {
…   return `${minutes} min`;
… };
undefined
> console.log(formatRuntime);
[Function: formatRuntime]
undefined
> typeof formatRuntime
'function'
> const helpers = [formatRuntime];
undefined
> helpers[0](104)
'104 min'

The first input is a const line like the ones you already write, with a function on the right of =. The undefined after it means the statement itself has no value to show, so you can ignore it.

Logging formatRuntime without parentheses doesn’t call the function. Node prints the function itself, [Function: formatRuntime], and then undefined, which is the REPL showing what console.log() returns. typeof reports 'function' for formatRuntime, the way it reports 'number' for 104.

If a function is a value, can it go where other values go? The last two inputs answer that. The array holds the function, not a result. helpers[0] reaches that function, and the (104) after it calls it, with the same result as formatRuntime(104). So a function’s name refers to a value, like any variable you’ve written. The parentheses are what make the call.

Buttons like this one, here and later in the course, open a chat with your mentor, with the question already typed and the paragraph above attached. You can send it as it is, or change it to ask what you’re really wondering.

Write Arrow Functions

Much of the JavaScript you’ll read stores small helpers in const variables the way you stored formatRuntime, and it often uses a shorter form too.

The versions below declare formatRuntime again with const. You can’t redeclare a const variable in the same REPL session, so try them in a script. Save each one in a file named forms.js, replacing the previous version, and run node forms.js.

A function expression defines a function where a value goes, such as on the right of =. The one from the REPL has no name after the function keyword, so it’s an anonymous function expression. Node still printed [Function: formatRuntime] because JavaScript gives an anonymous function the name of the const variable it’s first stored in. You call it through that variable:

Language: JavaScript
const formatRuntime = function (minutes) {
  return `${minutes} min`;
};

console.log(formatRuntime(99));

It prints the same kind of label as before:

Language: Program Output
99 min

Compare it with a declaration, function formatRuntime(minutes) { ... }. The name has moved to the const variable, and the definition ends with }; because the whole thing is one const statement.

An arrow function is a shorter way to write a function expression. You drop the function keyword and put => after the parameters. Arrows differ from other functions in a few ways that matter later, such as how this works, but that’s all you need about them for now:

Language: JavaScript
const formatRuntime = (minutes) => {
  return `${minutes} min`;
};

console.log(formatRuntime(116));

The arrow returns the same kind of label as the function expression:

Language: Program Output
116 min

The parentheses before => hold the parameter list. This course always puts parameters in parentheses, even a single one, as in (minutes). You’ll also see a single parameter written without them, minutes => ..., in other code, and it means the same thing. Several parameters are separated by commas, as in (title, minutes). With no parameters, the parentheses stay, empty: () => "Snacks at 7:30".

Choose the Arrow’s Body

An arrow’s body determines how it returns a value. When the body is a single expression, you can drop the braces and the return. This is a concise body, and the arrow returns the expression’s value for you:

Language: JavaScript
const formatRuntime = (minutes) => `${minutes} min`;

console.log(formatRuntime(125));

Same helper, now on one line:

Language: Program Output
125 min

The arrow with a concise body is the form you’ll write most in this course, because it keeps short helpers compact.

Why not keep the braces and drop only the return? Because braces mark a body, and a body returns undefined unless a return statement says otherwise. You can confirm this with one more version:

Language: JavaScript
const formatRuntime = (minutes) => {
  `${minutes} min`;
};

console.log(formatRuntime(148));

This time, the label never comes back:

Language: Program Output
undefined

The function builds the label inside the body and then discards it.

A concise body can return an object too, such as a fresh entry for a film Tomás adds to the list. Wrap the object in parentheses:

Language: JavaScript
const newEntry = (title) => ({ title: title, votes: 0 });

console.log(newEntry("Coco"));

The call returns the whole object:

Language: Program Output
{ title: 'Coco', votes: 0 }

Don’t leave out those parentheses. After =>, a { always starts a body, so (title) => { title: title } returns undefined.

Build Tomás’s Helpers

The picker will need small helpers it can use on every film, and arrows stored in const variables are how you’ll write them. The first two are formatRuntime, which you already have, and isShort, which says whether a film fits Tomás’s limit of 120 minutes.

Before you read on, write isShort yourself as an arrow with a concise body. It takes the minutes and returns true or false. Then compare your version with this script. Create a file named helpers.js in a folder for this course and save it there:

Language: JavaScript Filename: helpers.js
const formatRuntime = (minutes) => `${minutes} min`;
const isShort = (minutes) => minutes <= 120;

const watchlist = [
  { title: "Paddington 2", minutes: 104, genre: "comedy",
    seenBy: ["Tomás", "Aisha"], votes: 3 },
  { title: "Spirited Away", minutes: 125, genre: "animation",
    seenBy: ["Priya"], votes: 2 },
  { title: "The Grand Budapest Hotel", minutes: 99,
    genre: "comedy", seenBy: ["Kenji", "Lucía"], votes: 0 },
  { title: "Arrival", minutes: 116, genre: "sci-fi",
    seenBy: [], votes: 3 },
  { title: "Coco", minutes: 105, genre: "animation",
    seenBy: ["Aisha", "Priya", "Kenji"], votes: 4 },
  { title: "Inception", minutes: 148, genre: "sci-fi",
    seenBy: ["Tomás"], votes: 1 },
];

for (const film of watchlist) {
  const runtime = formatRuntime(film.minutes);
  console.log(film.title, runtime, isShort(film.minutes));
}

The watchlist array lists all the friends’ films, with each film’s genre, who has seen it, and its votes. These helpers only read title and minutes, but the picker will use the other fields as it grows, so keep this file. Run it from the same folder in your terminal:

Language: Shell
$ node helpers.js
Paddington 2 104 min true
Spirited Away 125 min false
The Grand Budapest Hotel 99 min true
Arrival 116 min true
Coco 105 min true
Inception 148 min false

You call both helpers by name, with parentheses, like any function. The difference is that each one is a value stored in a const variable. For more on the forms an arrow can take, see MDN’s Arrow function expressions page.

Before you move on, check that you can read and write arrows with either kind of body. Try each one in your head first, then in the REPL or in helpers.js:

  1. Predict what shout("Coco") and newVote("Coco") return, and explain why. The helpers are const shout = (title) => { title.toUpperCase() }; and const newVote = (title) => ({ title: title, votes: 1 });.
  2. Rewrite this declaration as an arrow function with a concise body, stored in a const variable: function addVote(votes) { return votes + 1; }.
  3. In helpers.js, write isUnseen, an arrow with a concise body that takes a film record and returns true when nobody has seen it. Log isUnseen(watchlist[3]) and isUnseen(watchlist[0]).
  1. shout("Coco") returns undefined. The braces make a body, and the body has no return, so the function builds the uppercase title and discards it. Either drop the braces, (title) => title.toUpperCase(), or add return inside them. newVote("Coco") returns { title: 'Coco', votes: 1 } because the parentheses tell JavaScript to interpret the braces as an object literal.
  2. const addVote = (votes) => votes + 1; The body is one expression, so the arrow returns it without return.
  3. With const isUnseen = (film) => film.seenBy.length === 0;, the two calls log true for Arrival, whose seenBy is empty, and false for Paddington 2.

You’ve stored functions in variables and in an array, but so far you’ve only called them yourself. If a function is a value, you can also hand it to another function, which then decides when to call it. That’s what you’ll watch happen in the next lesson, Pass Functions to Functions.

Become a Member to join the conversation.