funciones-arrow-javascript

What are arrow functions and how to use them in JavaScript

  • 4 min

An arrow function in JavaScript is a concise syntax for defining an anonymous function that can be defined inline without the need to formally name it.

They are formally known as an “arrow function” due to the arrow notation (=>) used to define it (they can also be called lambda functions).

These functions offer a shorter way to write functions. They are especially useful in situations where you need to define a simple function that you will use only once.

Furthermore, they have specific behaviors related to the this context (which simplifies their use).

If you want to learn more, check out the Introduction to Programming Course

Basic Syntax

The syntax of a lambda function is as follows:

const functionName = (param1, param2, ...) => {
    // Code block
};
Copied!
  • functionName: The name of the variable that holds the lambda function.
  • param1, param2, …: The parameters that the function accepts.
  • =>: The arrow operator that defines the lambda function.
  • Code block: The body of the function that performs the desired operation.

Basic Example

const add = (a, b) => {
    return a + b;
};

console.log(add(5, 3)); // Output: 8
Copied!

In this example, add is a lambda function that takes two parameters (a and b) and returns their sum.

The this Context

One of the most important characteristics of lambda functions is that they do not have their own this context.

Instead, this is inherited from the context in which the function is defined. This can be useful when working with methods inside objects and you want to preserve the this context.

class Counter {
    constructor() {
        this.number = 0;
    }

    increment() {
        setTimeout(() => {
            this.number++;
            console.log(this.number);
        }, 1000);
    }
}

const counter = new Counter();
counter.increment(); // Output after 1 second: 1
Copied!

In this example, the lambda function inside setTimeout maintains the this context of the Counter object, allowing this.number to refer to the object’s property rather than a different context.

Limitations

Cannot be used as a constructor

Lambda functions cannot be used as constructors. They cannot be invoked with the new operator, and attempting to do so will result in an error.

const Works = () => {};
const instance = new Works(); // TypeError: Works is not a constructor
Copied!

They do not have arguments

Lambda functions do not have the arguments object that is available in traditional functions. If you need to access a function’s arguments, you should use rest parameters (...args).

const sumAll = (...numbers) => {
    return numbers.reduce((accumulated, current) => accumulated + current, 0);
};

console.log(sumAll(1, 2, 3, 4)); // Output: 10
Copied!

Common Uses of Lambda Functions