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.
To run the program:
In this JavaScript version:
We define a
vals()
function that returns an array with two values, mimicking the behavior of returning multiple values.In the
main()
function, we use array destructuring to assign the returned values to variablesa
andb
. This is similar to the multiple assignment in the original example.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.
We use
console.log()
instead offmt.Println()
for output.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.