- Javascript Function Return Multiple Values
- JavaScript Function Return
- Return Multiple Values as Array
- Return Multiple Values as Object
- Conclusion
- Returning Multiple Values from a Function
- Returning multiple values from a function using an array
- Returning multiple values from an function using an object
- Summary
- JavaScript How to Return Multiple Values? [Examples & Theory]
- Returning Multiple Values in JavaScript
- Solution 1: Return Multiple Values in an Array
- Solution 2: Return Multiple Values in an Object
- Wrap Up
- Возврат нескольких значений из метода в JavaScript
- 1. Вернуть массив
- 2. Вернуть объект
Javascript Function Return Multiple Values
In this article, you are going to learn how JavaScript function return multiple values. We will look at 2 ways to return multiple values from a function in JavaScript with examples.
JavaScript Function Return
Every function in JavaScript returns a value. If you don’t specify a return value, the function will return undefined or in the case of the constructor function, it will return the value of this .
Any manual return value can also be returned using the return keyword. The return value can be any data type. For example:
- Number — return 1
- String — return «Hello»
- Boolean — return true
- Object — return
- Array — return [1, 2, 3]
- . and so on
Generally, we use return only a single value from a function. But in some cases, we need to return multiple values.
If you want to return multiple values from a function, you can use the following 2 ways:
- Return an array
- Return an object
Return Multiple Values as Array
Directly you can’t return more than one value from a function. Until and unless you wrap them to a single entity.
One of the ways to return multiple values from a function is to return an array.
The following example returns the sum and product of two numbers as an array.
Now, you can call the function and store the returned array in a variable.
Then you can access the values using the index of the array.
function operate(a, b) < var sum = a + b; var product = a * b; // return them as an array return [sum, product]; >var result = operate(2, 3); console.log(result[0]); // 5 console.log(result[1]); // 6
In the latest update in JavaScript, you can also use destructuring to access the values.
This way results can be accessed using the variable name instead of the index .
function operate(a, b) < var sum = a + b; var product = a * b; // return them as an array return [sum, product]; >var [sum, product] = operate(2, 3); console.log(sum); // 5 console.log(product); // 6
Return Multiple Values as Object
Another way to return multiple values from a function is to return an object.
Objects are used to store data in key-value pairs. So, you have to create a key along with the value.
The following example returns the sum and product of two numbers as an object.
Now, you can call the function and store the returned object in a variable.
Then you can access the values using the key of the object either using dot notation or bracket notation .
function operate(a, b) < var sum = a + b; var product = a * b; // return them as an object return ; > var result = operate(2, 3); console.log(result.sum); // 5 console.log(result.product); // 6
Even in the case of objects, you can use destructuring to access the values.
In the case of array destructuring, the order of the variables matters. But in the case of object destructuring, the order of the variables doesn’t matter. Only the key matters.
function operate(a, b) < var sum = a + b; var product = a * b; // return them as an object return ; > var = operate(2, 3); console.log(sum); // 5 console.log(product); // 6
Conclusion
In this tutorial, you have learned how to return multiple values from a function in JavaScript and destructuring assignments to unpack the values from the returned array or object.
You have learned two ways to return multiple values from a function.
Now, you can return multiple values from a function in JavaScript.
Returning Multiple Values from a Function
Summary: in this tutorial, you will learn to define JavaScript functions that return multiple values.
JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.
Returning multiple values from a function using an array
Suppose the following getNames() function retrieves the first name and last name from a database in the backend or from the result of a third-party API call and returns them as elements of an array:
function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; // return as an array return [firstName, lastName]; >
Code language: JavaScript (javascript)
The following shows how to get the return value from the getNames() function:
let names = getNames();
Code language: JavaScript (javascript)
Because the names variable is an array, you can reference its elements using the square brackets, like this:
const firstName = names[0], lastName = names[1];
Code language: JavaScript (javascript)
In ES6, you can use the destructuring assignment syntax to unpack values from an array more intuitively, like this:
const [firstName, lastName] = getNames();
Code language: JavaScript (javascript)
In this code, the firstName and lastName variables will take the first and second elements of the return array.
Returning multiple values from an function using an object
If you want to assign a name to each returned value to make it more readable and easier to maintain, you can use an object:
function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; // return values return < 'firstName': firstName, 'lastName': lastName >; >
Code language: JavaScript (javascript)
Since the names of the properties are the same as the variables, you can shorten it using the object literal syntax extensions in ES6 as follows:
function getNames( ) < // get names from the database or API let firstName = 'John', lastName = 'Doe'; return < firstName, lastName >; >
Code language: JavaScript (javascript)
And you can get the return value as an object like this:
let names = getNames(); let firstName = names.firstName, lastName = names.lastName;
Code language: JavaScript (javascript)
If you want to unpack properties from an object, you can use the object destructuring syntax as follows:
let < firstName, lastName >= getNames();
Code language: JavaScript (javascript)
Summary
- JavaScript doesn’t support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object.
- Use destructuring assignment syntax to unpack values from the array, or properties from objects.
JavaScript How to Return Multiple Values? [Examples & Theory]
The easiest way to return multiple values in JavaScript is by returning an array of multiple elements.
Then, you can access the returned values like this:
let values = getVals() let first = values[0] let second = values[1]
If you were looking for a quick answer, then there you have it! But to write clean code, the above isn’t always the best way to return two values. Instead, you can return “labeled” values by returning an object.
This guide teaches you how to return multiple values in JavaScript in a couple of ways.
Returning Multiple Values in JavaScript
In JavaScript, you have probably written a bunch of functions that return a single value. For instance:
But what if you want to write a function that returns multiple values.
Solution 1: Return Multiple Values in an Array
A naive yet simple way to return multiple values is by returning the values in an array.
For example, let’s create a function that returns the sum and the product of two numbers:
Now, when you call this function, you need to store the returned array into a variable and then access the two values.
let results = sumMul(2, 5) let sum = results[0] let mul = results[1] console.log(sum, mul)
Also, thanks to the latest updates in JavaScript (ECMAScript 6), you can restructure the return value more intuitively.
So instead of storing the returned value into a variable and then one by one picking the values from it, you can use shorthand. Here is how:
let [sum, mul] = sumMul(2, 5) console.log(sum, mul)
This code looks already more understandable.
But there is another way to return multiple values, which is even more intuitive and maintainable.
Solution 2: Return Multiple Values in an Object
Instead of returning the values in an array, you can place them inside an object and label the values. This makes it easier and more intuitive to access.
Let’s re-write the sumMul function in the previous example to employ this strategy:
If you now call this function, there is a more intuitive way to access the returned values:
let result = sumMul(2, 5) let sum = result.sum let mul = result.mul console.log(sum, mul)
As you can see, now you can reference the return values by their name. This makes the code more readable and less error-prone. Now it’s harder to accidentally mess up with the values as they are labeled clearly.
Wrap Up
Today you learned how to return multiple values from a function in JavaScript.
To recap, there are two ways to do it:
- Return an array of multiple values. This is the most obvious and straightforward way. However, it lacks readability as you need to refer to the returned values by index.
- Return an object with “labeled” values. This approach requires slightly more code but is the most reliable. By labeling the return values, it’s hard to mess things up. This is because you can refer to the returned values by their names.
Возврат нескольких значений из метода в JavaScript
В этом посте мы обсудим, как вернуть несколько значений из метода в JavaScript.
1. Вернуть массив
Идея состоит в том, чтобы упаковать возвращаемые значения внутри массива и вернуть этот массив из метода. В следующем примере кода показано, как это реализовать:
В следующем коде используется присваивание деструктуризации распаковывать значения из массивов в соответствующие переменные.
2. Вернуть объект
Другой подход состоит в том, чтобы упаковать возвращаемые значения внутри объекта с соответствующими метками и вернуть объект из метода. В следующем примере кода показано, как это реализовать:
Код можно упростить, используя присваивание деструктуризации:
Это все о возврате нескольких значений из метода в JavaScript.
Средний рейтинг 5 /5. Подсчет голосов: 22
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно