JavaScript Arrow Functions
š¹ 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
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.