What are Arrow Functions?
Arrow functions were introduced in ES6 (ECMAScript 2015) and provide a more concise syntax to write functions in JavaScript. They are especially useful for writing short functions and callbacks.
Traditional function declaration:
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
Output:
5
The same function using an arrow function syntax:
const add = (a, b) => a + b;
console.log(add(2, 3));
Output:
5
Syntax Variations
1. No parameters:
const greet = () => console.log("Hello!");
greet();
Output:
Hello!
2. Single parameter (no parentheses needed):
const square = n => n * n;
console.log(square(4));
Output:
16
3. Multiple parameters (parentheses required):
const multiply = (a, b) => a * b;
console.log(multiply(3, 7));
Output:
21
4. Multiple lines (need curly braces and explicit return):
const divide = (a, b) => {
if (b === 0) return "Cannot divide by zero";
return a / b;
};
console.log(divide(10, 2));
console.log(divide(10, 0));
Output:
5 Cannot divide by zero
Arrow Functions and this
Keyword
Arrow functions do not bind their own this
. Instead, they inherit it from the surrounding lexical context. This makes them especially useful in callbacks and methods like setTimeout
or array methods like map()
.
Example with setTimeout
:
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
new Timer();
Output: (increments every second)
1 2 3 ...
If we had used a regular function inside setInterval
, it wouldn't have worked as expected due to how this
behaves.
When NOT to Use Arrow Functions
- As methods inside objects if you rely on
this
- When using constructors (arrow functions can't be used as constructors)
Example: Arrow function as object method (not recommended)
const person = {
name: "Alice",
greet: () => {
console.log("Hi, I'm " + this.name);
}
};
person.greet();
Output:
Hi, I'm undefined
Why? Because this
in arrow functions doesn't refer to the object (person
), but to the global context.
Quiz for Intuition
Question: What will be the output of this code?
const obj = {
count: 10,
log: function() {
setTimeout(() => {
console.log(this.count);
}, 1000);
}
};
obj.log();
Answer: It will print 10
because the arrow function captures the this
from the log
method's context.
Summary
- Arrow functions offer a concise syntax for writing functions.
- They do not have their own
this
,arguments
, orsuper
. - Great for short callbacks, array methods, and maintaining lexical
this
. - Avoid using arrow functions as object methods or constructors.