Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Functions  ›  Lesson

Arrow Functions

Arrow Functions 12 minArrow functions are a slimmer syntax for a function expression, but they are not just shorthand: they have no this or arguments of their own, borrowing both from the surrounding scope, and they can never be used as a constructor.

Arrow Functions

In short: (params) => expression is a slimmer way to write a function — but it's not just shorthand. An arrow function has no this and no arguments of its own; both are borrowed from the surrounding scope where the arrow was written. That makes arrows the right choice inside a callback that needs the outer this, and the wrong choice for an object method or a constructor.

function double(n) {...} next to the slimmer const double = n => n * 2, same result; a note that the classic function has its own this and arguments, while the arrow has neither and borrows them from the surrounding scope; a trap note that an arrow can never be a constructor

The same function, written two ways

For a plain calculation with no this involved, the two are interchangeable:

javascript

Both give 10. The arrow drops function and return entirely when the body is a single expression — pure convenience, nothing else changes yet.

Fixing this inside a callback

The real reason arrows exist: a regular function passed to setTimeout gets its own this, which is not the object you meant.

javascript

Because the arrow has no this of its own, this inside it means exactly what it meant one line above, in incArrow — counter. A regular function passed to setTimeout instead would get a this decided by how setTimeout calls it, not by where it was written — almost never what you want.

Borrowing arguments too

Arrows don't just skip their own this — they skip their own arguments object as well, and see the enclosing function's instead:

javascript

inner is an arrow, so arguments inside it isn't its own — it reaches out to regularOuter's arguments, which has length 3. An arrow function genuinely has no arguments binding of its own to shadow it.

Quick practice

quick drill

What does an arrow function use for this inside its body?

quick drill

Why is a regular function passed to setTimeout often the wrong choice inside an object method?

quick drill

What happens when you try new SomeArrow() on an arrow function?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy the arrow fixes it

A counter object's method uses setTimeout(function () { this.count++; }, 0) and this.count comes out wrong, but switching to setTimeout(() => { this.count++; }, 0) fixes it. Explain why, in terms of what each kind of function uses for this.