Skip to content
jshacks.dev
Functions

Function Declarations Expressions and Arrow Functions Compared

Compare function declarations, expressions and arrow functions on hoisting, this, arguments, new and prototypes, with exact Node.js 24 output.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, npm, Vite and TypeScript logos.

JavaScript has three everyday ways to write a function, and they differ on five points that decide which one is correct for a given job: when the function exists, what this means inside it, whether it has an arguments object, whether it can be used with new, and whether it has a prototype. Declarations and expressions share almost all their behavior, and differ only in when they come into existence. Arrow functions differ from both in how they treat this, arguments and new, and that is the reason you cannot swap them blindly. This post puts the three side by side on Node.js 24 with exact output for each difference, so that you can see what changes if you rewrite one as another. A shorter comparison of just the first two forms is in the post on declarations and expressions, and this one adds arrows to the picture.

The three forms

JavaScript
function declaration(a, b) {
  return a + b;
}

const expression = function (a, b) {
  return a + b;
};

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

console.log(declaration(1, 2), expression(1, 2), arrow(1, 2));
console.log(declaration.name, expression.name, arrow.name);
Text
3 3 3
declaration expression arrow

All three compute the same value and get a name from where they are defined. The arrow form has a short body syntax: with no braces, the expression after => is the return value, and returning an object literal needs parentheses, () => ({ ok: true }). The comparison table below summarizes everything that follows.

DeclarationExpressionArrow
Hoisted with its bodyyesnono
Own thisyesyesno, takes it from the surrounding code
Own argumentsyesyesno
Can be used with newyesyesno
Has a prototypeyesyesno
Can be a generatoryesyesno

When the function exists

JavaScript
console.log(early(2));

function early(n) {
  return n * 2;
}

try {
  later(2);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const later = (n) => n * 2;
Text
4
ReferenceError: Cannot access 'later' before initialization

A declaration is hoisted with its body, so it can be called above its line. An expression or an arrow function assigned to a const exists only after its line runs, and calling it earlier throws. This makes declarations convenient for top-level helpers that you want to put below the main code, and makes arrows and expressions predictable, since the order of lines is the order of availability.

The value of this

A regular function gets its this from how it is called. An arrow function has no this of its own and uses the one from the code around it.

JavaScript
const timer = {
  seconds: 0,
  startRegular() {
    return [1, 2].map(function () {
      return this === undefined;
    });
  },
  startArrow() {
    return [1, 2].map(() => this === timer);
  },
};

console.log(timer.startRegular());
console.log(timer.startArrow());
Text
[ true, true ]
[ true, true ]

In the regular callback, this is undefined because a plain call in strict code has no owner, and map calls the callback that way. In the arrow callback, this is the timer object, since the arrow took it from startArrow. That is the reason arrows are the default for callbacks inside methods. The other side is that an arrow is wrong for a method that needs its own this.

JavaScript
const counter = {
  count: 3,
  regular() {
    return this.count;
  },
  arrow: () => this?.count,
};

console.log(counter.regular(), counter.arrow());
Text
3 undefined

The arrow's this is the module's this, which is undefined at the top of an ES module, so this?.count gives undefined. In a CommonJS file, this at the top is module.exports, an empty object, and the result is also undefined. Do not use an arrow function as an object method or a prototype method that reads this.

arguments

Regular functions have an arguments object, an array-like list of everything passed. Arrows do not, and use the one of the nearest enclosing regular function, if there is one.

JavaScript
function regular() {
  return arguments.length;
}

function outer() {
  const inner = () => arguments[0];

  return inner("ignored");
}

const arrow = (...args) => args.length;

console.log(regular(1, 2, 3), outer("from outer"), arrow(1, 2, 3));
Text
3 from outer 3

Use rest parameters, ...args, in new code: they are a real array, they work in arrows and they make the parameter list honest. A top-level arrow that mentions arguments throws a ReferenceError in an ES module.

new and prototype

JavaScript
function Point(x) {
  this.x = x;
}

const ArrowPoint = (x) => {
  this.x = x;
};

console.log(new Point(1));
console.log(typeof Point.prototype, typeof ArrowPoint.prototype);

try {
  new ArrowPoint(1);
} catch (error) {
  console.log(error.message);
}
Text
Point { x: 1 }
object undefined
ArrowPoint is not a constructor

An arrow function has no prototype property and no internal constructor behavior, so new fails. Use a class for constructors today, and a regular function only for old code. The same lack of a prototype means arrows are slightly lighter objects, though no one should pick them for that.

Names and stack traces

All three get a name when assigned to a variable, so stack traces are readable. An arrow passed inline has no name, and shows as <anonymous>, so when a callback matters, give it a name through a variable or use a named function expression.

JavaScript
const handlers = [
  function named() {},
  () => {},
  (() => () => {})(),
];

console.log(handlers.map((fn) => JSON.stringify(fn.name)));
Text
[ '"named"', '""', '""' ]

The first array entry is a named function expression. The second, an arrow written directly in an array literal, gets no name from the array, and the third was returned from another function. Names help when you read an error report.

Generators, async and methods

A generator must be a regular function: function* has no arrow version. async works with all three, async function, async function () {} and async () => {}. Inside a class or an object literal, the method shorthand name() {} is neither a declaration nor an arrow: it is a method, it has its own this, and it cannot be used with new.

JavaScript
async function a() {}
const b = async function () {};
const c = async () => {};

console.log(a.constructor.name, b.constructor.name, c.constructor.name);
Text
AsyncFunction AsyncFunction AsyncFunction

Recursion and self-reference

A function that calls itself needs a name to call. A declaration has one, and a named function expression has one that is visible only inside it. An arrow function assigned to a const can call itself through the variable, which works because the call happens after the assignment. The case to avoid is an arrow function inside a larger expression that has no variable name, since it has nothing to refer to.

JavaScript
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));

function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}

console.log(factorial(5), fib(10));
Text
120 55

Both forms work here. If the variable is later reassigned, the arrow's recursive call follows the reassignment, and a named function expression such as const f = function inner() { inner() } does not, which is a small reason to use that form for functions that can be wrapped or replaced.

Default parameters and rest

All three forms accept default values, destructuring and rest parameters in the same way, so none of those features should drive the choice. What does differ is that an arrow function with a single plain parameter may omit the parentheses, n => n * 2, which formatters usually rewrite to (n) => n * 2 for consistency, and that an arrow function with a body in braces needs an explicit return. Forgetting the return in a braced arrow is a frequent source of undefined results, as in list.map((n) => { n * 2 }), which returns an array of undefined.

How to choose

We follow four rules. A top-level helper in a module is a declaration, which reads well and is available throughout the file. A callback, a short function passed to map, filter, then or an event handler is an arrow, and it keeps the this of its surroundings. A function stored in a variable or exported as a value is an arrow when it is short and does not need this, and a named function expression or declaration when it is long, recursive or important in stack traces. An object or class method uses the method shorthand, and a constructor is a class.

Where this advice stops

Style guides differ, and some teams use arrows for everything except methods, which works. A linter rule such as func-style or prefer-arrow-callback enforces a team's choice. Be careful when converting code between forms: a regular callback that uses this or arguments changes meaning when it becomes an arrow, and the tests may not notice. In a class field, handler = () => {} is an arrow that captures the instance's this, which is the usual way to pass a method as a callback without bind, at the cost of one function per instance.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.