Course outline · 0% complete

0/29 lessons0%

Course overview →

Function expressions and arrow functions

lesson 6-2 · ~9 min · 19/29

Functions are values

Why does this matter? Because half of JavaScript's standard library takes a function as input: array methods (unit 7) ask what to do with each item, timers ask what to run later, servers ask what to do per request. Handing code around like that only works if a function is a value you can store and pass.

In JavaScript a function is a value like 42 or "hi". You can store one in a variable:

const double = function (n) {
  return n * 2;
};

That is a function expression. Since 2015 there is a shorter spelling you will see everywhere, the arrow function:

const double = n => n * 2;

Reading the arrow forms:

  • n => n * 2: one parameter, and the body is a single expression that is returned automatically (no return keyword, no braces).
  • (a, b) => a + b: two or more parameters need parentheses.
  • () => "hi": no parameters, empty parentheses.
  • n => { const d = n * 2; return d; }: braces make a full body, and then you must write return yourself.

Python's lambda n: n * 2 is the closest cousin, but arrows are not limited the way lambdas are. Arrows matter enormously in unit 7, where you hand them to array methods.

Code exercise · javascript

Three ways to define a function as a value. Run it, then try rewriting double as an arrow yourself.

Code exercise · javascript

Your turn. Write two arrow functions: square(n) returning n * n, and isEven(n) returning true when n divides evenly by 2 (use % from lesson 1-2 and === from lesson 2-3). Print square(6) and isEven(7).

Quiz

Which arrow function correctly returns n + 1?