Skip to main content

Arrow Functions

Introduced in ES6 (2015), Arrow Functions provide a concise syntax for writing function expressions. They are wildly popular and form the backbone of modern frameworks like React.

Basic Syntax

We drop the function keyword and use an arrow =>.

// Traditional Expression
const add = function(a, b) {
return a + b;
};

// Arrow Function
const addArrow = (a, b) => {
return a + b;
};

Implicit Returns

Arrow functions become incredibly powerful when the logic shrinks to a single line. If your function only calculates and returns an expression, you can drop the {} braces and the return keyword!

const multiply = (a, b) => a * b;

console.log(multiply(5, 5)); // 25

If you only have one parameter, you can even drop the parentheses around the parameter!

const square = num => num * num;

console.log(square(4)); // 16

The Lexical this

The most crucial technical difference between normal functions and Arrow functions surrounds the this keyword.

  • Normal Functions: Bound to the object that calls them.
  • Arrow Functions: Do not have their own this binding. They inherit this from the parent scope (lexical scoping). This makes them fantastic for callbacks inside class methods.