Regular:
function add(a, b) {
return a + b;
}
Arrow:
const add = (a, b) => a + b;
they're both called the same way:
add(2, 3)
Regular:
function greet() {
return "Hi";
}
Arrow:
const greet = () => "Hi";
they're both called the same way:
greet()
Regular:
const person = {
name: "Alex",
greet: function() {
return "Hi, I'm " + this.name;
}
};
Arrow:
const person = {
name: "Alex",
greet: () => {
return "Hi, I'm " + this.name;
}
};
when using the arrow method, 'this' is not a name. It's whatever 'this' was outside the object you defined with the arrow --usually a global object (window in browsers). Arrow functions (functions defined using arrows) never change 'this.'
this)new with them)this context is neededSay you're in a function and you want to use this inside a callback:
function Timer() {
this.seconds = 0;
// 👇 Regular function here would break
setInterval(function () {
this.seconds++;
console.log(this.seconds); // ❌ NaN or undefined
}, 1000);
}
Here, this inside setInterval does not refer to the Timer object.
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++; // ✅ works as expected
console.log(this.seconds);
}, 1000);
}
Arrow function uses this from the Timer function — the outer scope.>