JavaScriptEasy
What is an arrow function?
An arrow function ((a, b) => a + b) is a compact function expression that does not have its own this, arguments, super or new.target; it uses those from the surrounding scope.
Syntax variations
- One parameter:
x => x * 2(parentheses optional). - Expression body returns automatically:
(a, b) => a + b. - Block body needs an explicit
return:(a, b) => { return a + b; }. - Returning an object literal needs parentheses:
() => ({ ok: true }).
Lexical this
This is the real reason arrow functions exist. Inside a method, a callback written as a normal function gets its own this (often undefined), while an arrow function keeps the method's this. That makes arrows ideal for callbacks inside methods, timers and promise chains.
When NOT to use an arrow function
- Object methods that need
thisto be the object:{ count: 0, inc: () => this.count++ }will not work. - Constructors: arrows cannot be called with
newand have noprototype. - Event handlers that rely on
thisbeing the element (useevent.currentTargetinstead, or a normal function). - When you need the
argumentsobject (use rest parameters instead anyway).
Interview tip
Explain that this in an arrow is decided where the arrow is defined, not where it is called.
Code example
js
1const double = (n) => n * 2;2const makeUser = (name) => ({ name, createdAt: 2026 }); // parentheses to return an object3console.log(double(4), makeUser("Ada"));45class Timer {6 seconds = 0;7 start() {8 // arrow keeps `this` from start(), so it points to the Timer instance9 const id = setInterval(() => {10 this.seconds++;11 if (this.seconds === 3) {12 clearInterval(id);13 console.log("done at", this.seconds); // done at 314 }15 }, 10);16 }17}18new Timer().start();1920const counter = {21 count: 0,22 isCounterArrow: () => this === counter, // arrow: `this` comes from outside the object23 incMethod() {24 this.count++;25 return this.count;26 },27};28console.log(counter.isCounterArrow()); // false - the arrow did not get the object as `this`29console.log(counter.incMethod()); // 1
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.