javascript-retornos-funcion

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

  • 3 min

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

In JavaScript, the keyword return is used to specify the value to be returned.

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;
}
Copied!

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); 
Copied!

In this case,

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

Types of Function Returns in JavaScript

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

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"
Copied!

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
Copied!

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
Copied!

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

Implicit Return

In JavaScript arrow functions, an implicit return can be used.

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

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

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

Functions Without Return

If a function does not explicitly return a value using return, or if the end of the function is reached without a return, undefined is automatically returned.

function doNothing() {
    // No explicit return
}

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

Practical Examples

Let’s see some practical examples that illustrate how to use returns in real (or more realistic) situations.