Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Arrow functions

In JavaScript a function is a value just like a number or a string: you can put it into a variable and pass it around. Short functions have a compact form with an arrow => — arrow functions. Modern code uses them everywhere.

A function in a variable

A function can be created without a name and stored in a variable right away. This is called a function expression, and the function is called by the variable's name:

const square = function (n) {
  return n * n;
};
 
console.log(square(5)); // 25

There is one difference from a normal declaration: such a function cannot be called before the line where it is created.

Arrow syntax

An arrow function is a shortened function expression. The word function is dropped, and an arrow => goes between the parameters and the body:

const square = (n) => {
  return n * n;
};
 
console.log(square(5)); // 25

It works the same way: it takes arguments and returns a result with return.

Short body

If the body is a single expression, the curly braces and return can be dropped. The expression's result is returned automatically — this is called an implicit return:

const square = (n) => n * n;
 
console.log(square(5)); // 25

One line instead of three — that is exactly why arrow functions are so popular.

Parameters

With no parameters you write empty parentheses, and several parameters are separated by commas. With exactly one parameter the parentheses can be left out, but many people keep them for consistency:

const sayHi = () => 'Hi!';
const add = (a, b) => a + b;
const double = n => n * 2;
 
console.log(sayHi());     // Hi!
console.log(add(2, 3));   // 5
console.log(double(4));   // 8

Longer body

If the function needs several lines, the body goes in curly braces. Then return is written explicitly again:

const formatPrice = (amount) => {
  const rounded = amount.toFixed(2);
  return `$${rounded}`;
};
 
console.log(formatPrice(9.5)); // $9.50

When to use which

Regular function declarations suit large functions that form the backbone of a program. Arrow functions are good for short actions, especially when a function is passed into another function — see the lesson on callbacks. Arrow functions also behave differently with this; that is covered in the objects chapter.

Common mistake

If you put the body in curly braces, the implicit return stops working. A function without return returns undefined:

const double = (n) => { n * 2 };
 
console.log(double(4)); // undefined

Either drop the curly braces — (n) => n * 2 — or add a return inside.

Thanks for reading!

Donate to the site — we work hard for you.