Arrow Functions

“Fat arrow functions,” commonly known just as “arrow functions,” provide a modern alternative syntax to the traditional function keyword.

The Syntax Evolution

There are now three main ways to define essentially the same mathematical logic:

// 1. Traditional function declaration
function add(x, y) {
  return x + y;
}

// 2. Function expression assigned to a variable
const add = function(x, y) {
  return x + y;
};

// 3. Arrow function syntax
const add = (x, y) => {
  return x + y;
};

When to use Arrow Functions

Arrow functions are not just syntactic sugar; they behave differently than traditional functions in a few key ways:

  1. They are usually expressions: Arrow functions are almost always assigned to a variable (const or let) or passed anonymously.
  2. Implicit Returns: If your arrow function is a single line, you can omit the curly braces and the return keyword entirely: const add = (x, y) => x + y;
  3. No this binding: This is the most crucial difference. Arrow functions handle scoping in a fundamentally different way, making them the preferred choice for callbacks and nested functions (which we will cover next).
  4. Constructors: Fat arrow functions cannot be used as constructors (with the new keyword).