JavaScript ยท Chapter 44 of 55

JavaScript Arrow Functions

Arrow functions provide a shorter syntax for writing functions: `(a, b) => a + b` instead of `function(a, b) { return a + b; }`. Single expressions are implicitly returned without needing the `return` keyword.

Beyond brevity, arrow functions differ from regular functions in that they don't bind their own `this`, `arguments`, or serve as constructors.

Syntax variations

`(x) => x * 2` for a single expression, `() => {}` for no parameters, and `(a, b) => { return a + b; }` when a full block body is needed.

When to avoid them

Avoid arrow functions for object methods that need `this` to refer to the object, and for functions used as constructors with `new`.

Example 1 (javascript)
const square = x => x * x;
console.log(square(5));
Output
25

A single parameter and expression body need no parentheses or braces.

Example 2 (javascript)
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled);
Output
[2, 4, 6]

Arrow functions are especially popular as short callbacks.

Key points

  • Arrow functions use `=>` and support implicit returns for single expressions.
  • They do not have their own `this` binding.
  • They cannot be used as constructors with `new`.
  • They're commonly used for concise callbacks in map/filter/reduce.
๐Ÿ’ก Note: Single-parameter arrow functions can drop the parentheses: `x => x * 2` is valid.

๐Ÿ“ Quick Quiz

1. What does `x => x * 2` do?

2. Do arrow functions have their own `this`?

3. Can arrow functions be used with `new`?