Returning Multiple Values from a Function in JavaScript

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

Multiple values cannot be returned from a function in JavaScript but multiple values can be stored in an array or in an object and then the array or the object can be returned.

Introduction

In JavaScript, returning single values from a function can be achieved by calling the function. Let us understand just this simple program to return a single value from a function.

The above program will return: -

But what if the function has multiple values then what will it return?

The above program will return the last variable which is age and ignore all the other variables.

Therefore, to return all the values from a function there are two ways: -

  • By using an array
  • By using an object

Returning Multiple Values from a Function in JavaScript Using an Array

Let us create a function named user and enter two variables [name, age]. Now to return both variables we will return them using an array as shown in the following example.

Result

Returning Multiple Values from a Function in JavaScript Using an Object

By creating objects and labeling every return value, multiple values from a function can be returned.

Let us rewrite the above program of the user that has two variables name and age and return them by creating objects and labeling the return values.

Result

Merging objects

The different objects can be merged using the ... operator.

Example

Result

But if the objects have the same property name then the last value overrides the previous value. To prevent this we have deep copying. Use this Online JavaScript Formatter to format your code.

Assign() method

The objects can also be merged using the assign() method.

Syntax

It works similarly to the ... operator.

Conclusion

  • JavaScript does not return multiple values just by calling the function therefore it can be achieved using arrays or objects.
  • To return multiple values from a function using arrays, create an array of the variables that are to be returned and then call the array.
  • To return multiple values from a function using the object, you label the return values which does not mess the code up because you can refer to the values returned by their names but the code becomes a little lengthy.