Arrow Function
Learn JavaScript arrow functions for concise syntax. Use => instead of function, with variations for arguments and implicit returns for cleaner code.
Learn JavaScript arrow functions for concise syntax. Use => instead of function, with variations for arguments and implicit returns for cleaner code.
Arrow functions are a shorter syntax for writing functions. They use => instead of the function keyword.
// Regular functionfunction add(a, b) { return a + b;}
// Arrow functionconst add = (a, b) => { return a + b;};When the function body is a single expression, you can skip the curly braces and return:
const add = (a, b) => a + b;const double = (n) => n * 2;const greet = (name) => `Hello, ${name}!`;() => ...n => n * 2(a, b) => a + bArrow functions shine with callbacks:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]const evens = numbers.filter((n) => n % 2 === 0); // [2, 4]Arrow functions don’t have their own this — they inherit it from the surrounding scope. This is useful in callbacks where you want to keep the this from the outer context.
Regular functions create their own this, which is why methods on objects usually use regular function syntax.
Use arrow functions for callbacks, array methods, and short expressions. Use regular functions for object methods where you need this to refer to the object, and for functions that will be used as constructors.