Lesson 59 of 296
Arrow functions vs normal functions
What you will learn
- Every difference between arrow and normal functions
- When to use each one
On this page
The differences
| Feature | Normal function | Arrow function |
|---|---|---|
| Syntax | function (a) { return a; } | (a) => a |
Own this | Yes, set by how it is called | No, uses the surrounding this |
Can call / apply / bind change this? | Yes | No |
arguments object | Yes | No (use rest parameters) |
Can be used with new | Yes (declarations and expressions) | No, TypeError |
Has a prototype property | Yes | No |
| Implicit return | No | Yes, with an expression body |
| Hoisting | Declarations are hoisted | Follows its const/let variable (TDZ) |
Can be a generator (function*) | Yes | No |
arguments
Normal functions have a special array-like object called arguments with every argument passed:
function sum() {
let total = 0;
for (const n of arguments) total += n;
return total;
}
sum(1, 2, 3); 6Arrow functions do not have it. Use rest parameters instead, which work in both and give a real array:
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);Rest parameters are the modern choice everywhere.
No new
const Person = (name) => { this.name = name; };
new Person("Sam"); TypeError: Person is not a constructorWhen to use arrow functions
- Short callbacks:
map,filter,reduce,then, event handlers. - Callbacks inside methods that need the method's
this: timers, promises. - Small helpers stored in
const. - Class fields that must keep
thiswhen passed around.
When to use normal functions
- Object methods that use
this. - Constructors (or better, classes).
- Event listeners where you want
thisto be the element (or useevent.currentTarget). - Top-level named functions, if you want hoisting. Many teams prefer
functiondeclarations for main named functions because the name is clear in stack traces and they can be ordered freely in a file. - Generators.
How to say it in an interview
"Arrow functions are shorter and have implicit returns, but the important difference is that they do not have their own this or arguments; they take this lexically from the surrounding scope, and call, apply and bind cannot change it. They also cannot be used as constructors and have no prototype. I use them for callbacks, and normal functions or method syntax for object methods and anything that needs its own this."
Key words
| Word | Meaning |
|---|---|
arguments | An array-like object of all arguments, in normal functions only |
| Rest parameters | ...args, collects arguments into a real array |
| Lexical this | Taking this from the surrounding code |
| Constructor | A function that can be called with new |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.