Complete JavaScript Course Module 5: Beginner: Functions

Arrow Functions and Function Expressions

  • Beginner
  • Lesson 5.3
  • 4 min read
  • 19 of 76 in the course

In short

Arrow functions are a short, modern way to write JavaScript functions. Learn function expressions, arrow syntax, implicit return and when to use them. What is a function expression? In JavaScript, a function is a value, just like a number or a string.

Arrow functions are a short, modern way to write JavaScript functions. Learn function expressions, arrow syntax, implicit return and when to use them.

What is a function expression?

In JavaScript, a function is a value, just like a number or a string. That means you can store a function in a variable. This is called a function expression.

const greet = function (name) {
  return `Welcome back, ${name}!`;
};

console.log(greet("Lena"));
// Output: Welcome back, Lena!

The function has no name of its own after function. It is stored in the constant greet, and you call it with greet() as usual. Notice the semicolon at the end: the whole thing is one assignment statement, like const x = 5;.

There is one important difference from a function declaration: a function expression is not hoisted in the same way. You must create it before you call it.

// sayBye(); // Error: Cannot access 'sayBye' before initialization

const sayBye = function () {
  console.log("Goodbye!");
};

sayBye();
// Output: Goodbye!

Arrow function syntax

An arrow function is a shorter way to write a function expression. You drop the function keyword and put an arrow => after the parameters.

const add = (a, b) => {
  return a + b;
};

console.log(add(2, 3));
// Output: 5

Read => as "goes to": the parameters a and b go to the code in the curly braces. Arrow functions can be made even shorter in some cases.

One parameter: brackets are optional

const double = n => {
  return n * 2;
};

console.log(double(8));
// Output: 16

With exactly one parameter, you may leave out the round brackets. With zero or two or more parameters, you need them: () => ... or (a, b) => .... Many teams always write the brackets for consistency, and code formatters often add them for you.

Implicit return: one expression, no braces

If the body is a single expression, you can remove the curly braces and the return keyword. The result is returned automatically. This is called an implicit return.

const calculateTax = price => price * 0.2;
const formatPrice = (amount, currency = "USD") => `${amount.toFixed(2)} ${currency}`;

console.log(calculateTax(50));
console.log(formatPrice(19.5));
console.log(formatPrice(calculateTax(80), "EUR"));
// Output:
// 10
// 19.50 USD
// 16.00 EUR

toFixed(2) turns a number into a string with exactly two decimal places. Each of these functions fits on one line and reads almost like a sentence.

Common mistake: Adding curly braces but forgetting return. const square = n => { n * n }; returns undefined, because braces mean "a normal body", and a normal body needs return.

Returning an object

You will learn objects in the Objects module. For now, know that an object is a group of named values written with curly braces, like { name: "Sam", age: 30 }. Because curly braces after => mean "a body", you must wrap an object in round brackets to return it implicitly:

const createUser = (name, age) => ({ name: name, age: age });

console.log(createUser("Sam", 30));
// Output: { name: "Sam", age: 30 }

Without the round brackets, JavaScript would think { starts the function body and you would get undefined.

When are arrow functions a good choice?

SituationGood choice
Short calculations or small helpersArrow function with implicit return
Passing a function to another function (for example, to run when a button is clicked)Arrow function
A main, named function that you want hoisted and easy to findFunction declaration

Arrow functions shine when you pass a function as a value. You will do this a lot with arrays (in the Arrays module) and with events, as you will see in the Number Guessing Game project.

Note: Arrow functions also handle a special keyword called this differently from normal functions. You do not need this yet; it is covered later in the course, in the Objects module.

Practice exercise

Rewrite these two function declarations as arrow functions with implicit return, then test them in the console:

function isAdult(age) {
  return age >= 18;
}

function fullName(first, last) {
  return `${first} ${last}`;
}

Hint: Start with const isAdult = age => ... and const fullName = (first, last) => .... isAdult(20) should give true, and fullName("Ada", "Lovelace") should give "Ada Lovelace".

Key takeaways

  • A function expression stores a function in a variable, and it must be created before you call it.
  • Arrow functions use => and are a shorter way to write function expressions.
  • With one expression and no braces, an arrow function returns the result automatically.
  • To return an object directly, wrap it in round brackets: () => ({ ... }).
  • Use arrow functions for short helpers and for functions you pass to other code.