ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Arrow Functions

@thedevspaceio

šŸ¹ JavaScript Arrow Functions Cheatsheet

Arrow functions provide a shorter syntax for writing functions and do not bind their own this, making them ideal for callbacks and functional patterns.

āœ… Basic syntax āœ… Implicit return āœ… Single parameter āœ… Multiple parameters āœ… Returning objects āœ… this behavior āœ… When not to use arrow functions

#javascript #arrowfunctions #es6 #functions #this #syntax #webdev #frontend #coding


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