Skip to the content

Lesson 39 of 296

Function expressions and arrow functions

What you will learn

  • That functions are values
  • Function expressions
  • Arrow functions and their short forms
  • Callbacks: passing a function to another function
  • Function declarations vs expressions: hoisting
  • When to use which style
On this page

Functions are values

In JavaScript, a function is a value, just like a number or a string. You can store it in a variable, pass it to another function, and return it from a function. This is described by saying JavaScript has first-class functions.

Function declaration (Lesson 38)

function square(n) {
  return n * n;
}

Function expression

A function stored in a variable:

const square = function (n) {
  return n * n;
};

square(4);     16

The function itself has no name here. A function with no name is called anonymous.

Arrow functions

A shorter way to write a function expression, added in ES6:

const square = (n) => {
  return n * n;
};

Short forms:

If the body is one expression, you can remove the braces and return. The result is returned automatically (this is called an implicit return):

const square = (n) => n * n;

If there is exactly one parameter, the brackets around it are optional:

const square = n => n * n;

Many teams keep the brackets anyway, for consistency.

No parameters: empty brackets are required.

const sayHi = () => "Hi!";

Several parameters:

const add = (a, b) => a + b;

The object trap

To return an object with an implicit return, wrap it in round brackets:

Wrong:  const makeUser = (name) => { name: name };      returns undefined
Right:  const makeUser = (name) => ({ name: name });

In the wrong version, JavaScript reads { as the start of a function body, not an object.

Callbacks

A callback is a function you pass into another function, to be called later.

function runTwice(action) {
  action();
  action();
}

runTwice(() => console.log("Hi"));

Shows Hi twice.

Callbacks are everywhere in JavaScript:

setTimeout(() => {
  console.log("Two seconds later");
}, 2000);

button.addEventListener("click", () => {
  console.log("Clicked");
});

const doubled = [1, 2, 3].map((n) => n * 2);     [2, 4, 6]
  • setTimeout calls your function after a delay (2000 milliseconds = 2 seconds).
  • addEventListener calls your function when the button is clicked.
  • map calls your function once for every item in the array (Part 5).

Common mistake: passing the result instead of the function.

Wrong:  setTimeout(sayHi(), 1000);    runs sayHi straight away
Right:  setTimeout(sayHi, 1000);      passes the function to run later

Declarations vs expressions: hoisting

A function declaration can be called before the line where it is written:

greet();                     works
function greet() {
  console.log("Hi");
}

This works because JavaScript prepares function declarations before running the code. This behaviour is called hoisting.

A function expression or arrow function stored in const or let cannot be called before its line:

greet();                     ReferenceError: Cannot access 'greet' before initialization
const greet = () => console.log("Hi");

Part 5 explains hoisting in detail.

Arrow functions and this

Arrow functions also handle the special word this differently from normal functions. This matters a lot for objects and classes. Part 5 covers it fully. For now: do not use arrow functions as methods of an object if the method uses this.

Which style should you use?

SituationCommon choice
Short callbacks (map, filter, events)Arrow function
Small helper stored in a variableArrow function
Main named functions in a fileEither; follow your team's style
Object methods that use thisNormal function or method syntax

Common mistakes

  • Forgetting brackets when returning an object from an arrow function.
  • Adding { } to an arrow function but forgetting return, so it returns undefined.
  • Calling a callback straight away (fn()) instead of passing it (fn).
  • Calling a const function before its line.

How to say it in an interview

"Functions in JavaScript are first-class values, so they can be stored in variables, passed as callbacks and returned from other functions. Function declarations are hoisted, so they can be called before they appear; function expressions and arrow functions in const are not. Arrow functions give a shorter syntax with implicit returns, and they do not have their own this, so I do not use them as object methods that rely on this."

Key words

WordMeaning
First-class functionsFunctions can be used like any other value
Function expressionA function created as a value, often stored in a variable
Anonymous functionA function with no name
Arrow functionThe short () => {} function syntax
Implicit returnReturning a value without writing return
CallbackA function passed into another function to be called later
HoistingFunction declarations being available before their line

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.