Multiple Return Values in JavaScript

JavaScript doesn’t have built-in support for multiple return values like some other languages. However, we can achieve similar functionality using arrays or objects. In this example, we’ll use an array to return multiple values.

// This function returns an array with 2 values
function vals() {
    return [3, 7];
}

function main() {
    // Here we use array destructuring to assign the returned values
    const [a, b] = vals();
    console.log(a);
    console.log(b);

    // If you only want a subset of the returned values,
    // you can use array destructuring with a placeholder
    const [, c] = vals();
    console.log(c);
}

main();

To run the program:

$ node multiple-return-values.js
3
7
7

In this JavaScript version:

  1. We define a vals() function that returns an array with two values, mimicking the behavior of returning multiple values.

  2. In the main() function, we use array destructuring to assign the returned values to variables a and b. This is similar to the multiple assignment in the original example.

  3. To demonstrate ignoring a value, we use array destructuring with a placeholder (an empty space before the comma). This achieves the same effect as using the blank identifier in the original example.

  4. We use console.log() instead of fmt.Println() for output.

  5. There’s no need for explicit type declarations in JavaScript, as it’s a dynamically typed language.

While JavaScript doesn’t have native multiple return values, using arrays or objects to return multiple values is a common pattern. This approach provides similar functionality and flexibility.

Next, we’ll look at how to create functions that accept a variable number of arguments in JavaScript.