Language: EN

javascript-retornos-funcion

What are function returns and what types of function returns are there in JavaScript

The return of a function is the value that the function sends as a result after executing.

In JavaScript, the return keyword is used to specify the value that you want to return.

When a function reaches a return statement, the execution of the function stops and the specified value is “returned” to the place where the function was called.

The basic syntax for returning a value from a function is as follows:

function functionName() {
    return value;
}

Let’s see it with a simple example

function add(a, b) {
  return a + b; // Returns the sum of a and b
}

// Stores the returned value (7) in the result variable
let result = add(3, 4); 

In this case,

  • The add function calculates the value of a + b.
  • return returns the result of the operation to where the function was called.
  • The returned value (7) is stored in the result variable.

Types of function returns in JavaScript

In JavaScript, function return types can be of different kinds.

Primitive value return

Primitive values include data types such as numbers, strings, booleans, null, undefined, and symbols. A function can return any of these types as a result.

function getName() {
    return "Luis";
}

let name = getName(); // name will be "Luis"

Object return

JavaScript is an object-oriented language, and of course, a function can return objects.

function createPerson(name, age) {
    return {
        name: name,
        age: age
    };
}

let person = createPerson("María", 25);
console.log(person.name); // Output: María

Function return

JavaScript allows the creation of higher-order functions, which are functions that can return other functions.

function createAdder(x) {
    return function(y) {
        return x + y;
    };
}

let addFive = createAdder(5);
console.log(addFive(3)); // Output: 8

In this example, createAdder returns a function that adds the value x to the argument y.

Implicit return

In JavaScript arrow functions, you can have an implicit return.

That is, if the function consists of a single expression, you can omit the return keyword.

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

let result = multiply(4, 5); // result will be 20

Functions without return

If a function does not explicitly return a value using return, or if it reaches the end of the function without a return, it automatically returns undefined.

function doNothing() {
    // No explicit return
}

let result = doNothing(); // result will be undefined

Practical examples

Let’s look at some practical examples that illustrate how to use returns in real (or somewhat real) situations.