Skip to content
blog
2 min read

Arrow Function

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.

Basic Syntax

// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => {
return a + b;
};

Implicit Return

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}!`;

Parentheses Rules

  • No arguments — empty parens required: () => ...
  • One argument — parens optional: n => n * 2
  • Multiple arguments — parens required: (a, b) => a + b

Arrow Functions with Array Methods

Arrow 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]

The this Difference

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.

When to Use Which

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.