Arrow functions provide a shorter syntax for writing function expressions in JavaScript. Introduced in ES6, they are often more concise and do not have their own this, arguments, super, or new.target. Instead, they are best suited for callbacks, array methods, and small utility functions.
this from their surrounding (lexical) scope.new.arguments object.Arrow functions can be written in several forms depending on the number of parameters and the complexity of the function body.
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Single parameter
const square = x => x * x;
// No parameters
const greet = () => console.log("Hello!");
// Multiple lines (need return keyword)
const sum = (a, b) => {
const result = a + b;
return result;
};
For single-expression bodies, the value of the expression is returned automatically (implicit return). For multi-line bodies wrapped in { ... }, you must use an explicit return statement.
thisArrow functions do not bind their own this. Instead, they capture this from the surrounding lexical scope. Because of this, they are generally not suitable for defining object methods or constructors.
const person = {
name: "Alice",
greet: () => {
console.log("Hi " + this.name);
}
};
person.greet(); // Hi undefined
In the example above, this inside greet does not refer to person, so this.name is undefined. A regular function method would correctly bind this to the object.
add(2, 3) returns 5 in both regular and arrow function versions.square(4) returns 16 using the single-parameter arrow function.greet() logs "Hello!" to the console.sum(5, 7) returns 12 from the multi-line arrow function with an explicit return.person.greet() logs "Hi undefined" because this is not bound to the person object in an arrow function.Use this behavior to your advantage when you want this to come from the outer scope (for example, inside callbacks), but avoid arrow functions when defining object methods that rely on their own this.
map, filter, and forEach.this is desired (e.g., inside classes or components).this.new — they are not constructors.const makeUser = (name) => ({ name });return.setTimeout to log a message after 1 second.map() with an arrow function to double all numbers in an array.this inside both.