❤ Like
🔖 Save
🔗 Share
Eric Hu
Eric Hu

JavaScript Arrow Functions

@thedevspaceio

🏹 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

js
const add = (a, b) => {
  return a + b;
};
 
add(2, 3); // 5

Implicit return

When the function body is a single expression, you can omit the braces and return keyword.

js
const multiply = (a, b) => a * b;
 
multiply(4, 5); // 20

Single parameter

Parentheses are optional when there is exactly one parameter.

js
const square = (x) => x * x;
 
square(6); // 36

Returning objects

When returning an object literal, you must wrap it in parentheses to avoid confusion with the function body.

js
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.

js
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.

js
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.

@thedevspaceio
www.thedevspace.io