
JavaScript Arrow Functions
🏹 Arrow Functions: The Double-Edged Sword of Modern JavaScript
Arrow functions aren't just about saving keystrokes. They fundamentally change how this behaves, which is both their superpower and their Achilles' heel.
Unlike regular functions, arrow functions don't bind their own this. They inherit this from the surrounding parent context.
In this cheatsheet, we'll discuss superpower of the arrow functions, and the peculiar behavior of this that can lead to unexpected bugs if you're not careful.
#JavaScript #ArrowFunctions #ES6 #WebDevelopment #Programming #CodingTips #Frontend #React #NodeJS #SoftwareEngineering #CleanCode
Basic syntax
const add = (a, b) => {
return a + b;
};
add(2, 3); // 5Implicit return
When the function body is a single expression, you can omit the braces and return keyword.
const multiply = (a, b) => a * b;
multiply(4, 5); // 20Single parameter
Parentheses are optional when there is exactly one parameter.
const square = (x) => x * x;
square(6); // 36Returning objects
When returning an object literal, you must wrap it in parentheses to avoid confusion with the function body.
const makeUser = (name) => ({ name, active: true });
makeUser("Grace"); // { name: "Grace", active: true }this behavior
Arrow functions do not have their own this. They inherit this from the surrounding scope.
const team = {
name: "Engineering",
members: ["Ada", "Grace"],
logMembers() {
this.members.forEach((member) => {
console.log(`${member} is in ${this.name}`);
});
},
};
team.logMembers();
// "Ada is in Engineering"
// "Grace is in Engineering"Avoid arrow functions when
When you need a dynamic this, such as event listeners that rely on the element triggering the event.
const button = document.querySelector("button");
// Arrow function
button.addEventListener("click", () => {
console.log(this); // this points to the surrounding scope, not the button
this.classList.add("active");
});
// Regular function
button.addEventListener("click", function () {
console.log(this); // this points to the button element
this.classList.add("active");
});Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.