Arrow functions and regular functions look similar, and they behave differently in four specific ways. They differ in how this is worked out, in whether they have their own arguments, in whether they can be used with new, and in whether they are hoisted. Arrow functions are shorter to write and much more common. Regular functions are still the right tool in a handful of places, and this lesson shows you which is which.
The previous lesson in this module covered "Parameters and Return Values", and the next lesson in this module is about "Default Parameters, Rest and Function Tricks".
What is the syntactic difference?
An arrow function replaces the function keyword with an arrow and drops the name. When there is a single parameter, you can leave off the parentheses as well.
const double = function (n) {
return n * 2;
};
const triple = (n) => {
return n * 3;
};
const quadruple = (n) => n * 4;
console.log('double gives', double(2));
console.log('triple gives', triple(2));
console.log('quadruple gives', quadruple(2));
All three of them are functions, and all three of them behave in the same way when you call them. The last one uses the implicit return, which means that a single expression body is returned without you writing the return keyword.
That shorthand is where most arrow function mistakes come from. If you write a block body and forget the return, then the function gives back undefined.
const toRupees = (paise) => paise / 100;
function label(name) {
return 'Hello, ' + name;
}
console.log('toRupees gives', toRupees(24950));
console.log('label gives', label('Ada'));
// A block body needs an explicit return.
const broken = (n) => {
n * 2;
};
console.log('broken gives', broken(2));
How do they differ with this?
This is the difference that really matters. The this of a regular function depends on how it is called. An arrow function has no this of its own. It uses the this of the scope where it was written, and you cannot change that by calling it in a different way.
const timer = {
seconds: 0,
start() {
const arrowTick = () => {
this.seconds += 1;
};
const regularTick = function () {
this.seconds += 1;
};
arrowTick();
regularTick.call(this);
return this.seconds;
},
};
console.log('the timer reaches', timer.start());
Inside the method, this is the timer object. The arrow function picks that up automatically, because it was written inside the method. The regular function would lose it the moment it was called on its own, so it has to be given the right this with .call(this) or with .bind(this).
That is the whole rule: use an arrow function when you want to keep the surrounding this, and use a regular function when you want the call site to decide it. The full story of this, including what happens when a method is detached from its object, has its own lesson later in this tutorial, in the classes and prototypes module.
What about the arguments object?
A regular function has its own arguments, which is an array-like list of everything that it was called with. An arrow function does not have one of its own. It uses the arguments of whatever scope encloses it.
function outer() {
const arrowCount = () => arguments.length;
function regularCount() {
return arguments.length;
}
return { arrow: arrowCount(), regular: regularCount(1) };
}
console.log('with three arguments:', outer(1, 2, 3));
The arrow function sees three arguments, which are the ones of outer, while the regular function sees only the one that it was given. Outside a function entirely, an arrow has no arguments at all, and in an ES module, referring to it throws a ReferenceError.
The arguments object is also array-like rather than a real array. It has a length and numeric indexes, but it has none of the array methods.
function hasMap() {
return typeof arguments.map;
}
function countArgs(...args) {
return args.length;
}
console.log('arguments has a map method:', hasMap(1, 2));
console.log('rest parameters give a real array:', countArgs(1, 2, 3));
That is exactly why the rest parameter, which is covered next, is the better tool. It produces a real array, and it is the modern replacement for arguments in new code.
Can an arrow function be used as a constructor?
No. Arrow functions have no prototype property, so they cannot be called with new.
const Arrow = () => {};
try {
new Arrow();
} catch (error) {
console.log('caught:', error.constructor.name, '-', error.message);
}
function Regular() {}
const instance = new Regular();
console.log('a regular function works:', instance instanceof Regular);
The attempt throws a TypeError that says Arrow is not a constructor, while the regular function constructs an object in the normal way. If you need a constructible function, then you need a regular one. That is why the classes that you reach later on are built on regular function syntax under the hood.
Are arrow functions hoisted?
No. Only function declarations are hoisted. An arrow function that is stored in a const behaves exactly like any other const, so it cannot be used before its declaration runs.
console.log('a declaration gives', typeof declared);
function declared() {}
try {
console.log(typeof assigned);
} catch (error) {
console.log('caught:', error.constructor.name, '-', error.message);
}
const assigned = () => {};
The declaration reports 'function' because the engine registered it before it ran anything. The arrow function throws a ReferenceError with the message Cannot access 'assigned' before initialization, because the binding exists but has not been given a value yet.
Why are arrows so common in callbacks?
Because a callback is usually called by somebody else, with a receiver that you do not control. A regular function that you hand to setTimeout, to addEventListener, or to an array method gets a this that depends entirely on the caller. An arrow ignores all of that and keeps the this of the place where it was written.
const form = {
submitted: false,
handleSubmit() {
setTimeout(() => {
this.submitted = true;
console.log('submitted:', this.submitted);
}, 0);
},
};
form.handleSubmit();
The output is submitted: true. The arrow function was written inside handleSubmit, so its this is the form object no matter who ends up calling it. If the callback had been a regular function, then this would have belonged to whatever called it, and the assignment would have gone somewhere else entirely. It would even have thrown, in the strict mode that ES modules run in.
This is the practical reason that arrows dominate callback positions in modern JavaScript, and it is also the reason that they are the wrong choice for the methods of an object.
So which should I use?
| Situation | Use |
|---|---|
| Callbacks, event handlers, and array methods | Arrow function |
A short helper that should keep the surrounding this | Arrow function |
A method on an object that needs its own this | Regular function, or a shorthand method |
Something that must work with new | Regular function |
| Something that must be callable before its definition | Function declaration |
A function that needs its own arguments | Regular function with rest parameters |
As a working rule, reach for an arrow function unless you have a specific reason not to. It is shorter, it cannot be misused as a constructor, it has no arguments of its own to confuse you, and it takes its this from where it was written, which is what you want almost every time.
The differences in summary
- Arrows have no name of their own and they are not hoisted, so you must define them before you call them.
- An arrow with a single-expression body returns it implicitly, while a block body needs an explicit
return. - An arrow takes its
thisfrom the scope it was written in, and a regular function takes it from the call site. - An arrow has no
argumentsof its own, so use rest parameters instead. - An arrow cannot be used with
new, and it has noprototype. - For callbacks and array methods, arrows are the default choice.
Try it yourself: take an object with a counter and write two methods on it. Write one as a shorthand method and one as an arrow function property. Call both of them as counter.increment() and watch the arrow version fail to update the counter, because its this is not the object. Then rewrite the arrow version as a shorthand method and confirm that it works. That single experiment explains the rule better than any amount of reading.