1195

I am trying to return two values in JavaScript. Is this possible?

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};
5
  • 1
    you can solve this by using callbacks, if you are willing to do so, see my answer. People forget that you can "return multiple values" easily with JS, using tuples or even: callbacks! Jan 27, 2017 at 5:10
  • 31
    The answers are outdated. It is now possible. 2ality.com/2014/06/es6-multiple-return-values.html Apr 27, 2017 at 5:54
  • 13
    You technically are still returning a single object/array, it's just the deconstruction that is simpler in ES6. Apr 15, 2019 at 0:36
  • 3
    I believe Andrea is referring to "destructuring". But, yes, you still aren't returning more than one item from a function: that one item can be an object containing any number of keys or an array with n items.
    – Crates
    Jun 22, 2021 at 14:10
  • You can consider this tutorial page
    – Cadoiz
    Oct 24, 2022 at 14:27

20 Answers 20

1828

No, but you could return an array containing your values:

function getValues() {
    return [getFirstValue(), getSecondValue()]
}

Then you can access them like so:

const [first, second] = getValues()

This is called destructuring assignment and is supported by every major JS environment. It's equivalent to the following:

const values = getValues()
const first = values[0]
const second = values[1]

You can also return an object if you want to assign a name to each value:

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    }
}

And to access them:

const {first, second} = getValues()

Which is the same as:

const values = getValues()
const first = values.first
const second = values.second

It is highly recommended to return an object instead of an array unless the values make sense as a simple tuple, e.g. a coordinate pair [x, y]. With an array, it's easy to forget which value is which, it's harder to add more values later, and it's marginally more difficult to correctly type with TypeScript or JSDoc.

6
  • 2
    @alexela Sure you can simply use var dCodes = newCodes().dCodes; var dCodes2 = newCodes().dCodes2 However, you will call the function twice which may be a waste of resources if it is complex. Feb 25, 2016 at 21:39
  • 15
    @VadimKirilchuk No need to call it twice with destructuring assignment — ex. const { dCodes, dCodes2 } = newCodes(); Jan 30, 2017 at 6:31
  • 7
    as other answers said (and comments implied), ES6 brings a few options here. 3 to be exact: (1) object property shorthand return {dCodes, dCodes2} work just the same as @Intelekshual mentioned and (2) using the same function you could simply access them with destructuring arrays [dCodes, dCodes2] = newCodes() or (3) objects ({dCodes, dCodes2} = newCodes()) (no need to use a declaration there @Taylor, though a var would be more fitting for the current Sasha's example).
    – cregox
    Mar 18, 2017 at 9:09
  • 1
    How should I write jsDoc descriptions for functions that return multiple values in an array [value1, value2] or in an object { a: value1, b: value2 }?
    – Julius
    Aug 13, 2021 at 21:26
  • 1
    Also if you need to specify this kind of type on Typescript then you can simply replace the values with their types, e.g. function foo(): [string, string] { /* ... */ } Nov 6, 2023 at 14:34
303

You can do this from ECMAScript 6 onwards using arrays and "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).

It allows you to assign to 1+ variables simultaneously:

var [x, y] = [1, 2];
x; // 1
y; // 2

// or

[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4

You can also use object destructuring combined with property value shorthand to name the return values in an object and pick out the ones you want:

let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3

And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, .... What really happens there is not what might seem. An expression in return statement — 1, 2, 3 — is nothing but a comma operator applied to numeric literals (1 , 2, and 3) sequentially, which eventually evaluates to the value of its last expression — 3. That's why return 1, 2, 3 is functionally identical to nothing more but return 3.

return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;
5
  • 2
    Weird and interesting thing about the last example: for a function foo(){return 1,2,3;} doing console.log([].push(foo())) prints out 1.
    – Meredith
    Oct 25, 2013 at 20:45
  • 1
    why var [x, y] = [1, 2]; x; // 1 y; // 2 this does not work in chrome? raise an error ; ReferenceError: Invalid left-hand side in assignment Jun 8, 2014 at 5:25
  • @NaveenAgarwal Chrome does not yet fully support ECMAScript 6 in which destructing assignment is specified
    – gilbertbw
    Jul 15, 2014 at 10:50
  • 1
    Chrome v49 was released a week ago supporting "destructuring assignments" out-of-the-box. Mar 10, 2016 at 14:29
  • What would return (1, 2, 3); do? This could be added to the answer.
    – Cadoiz
    Oct 24, 2022 at 14:00
80

Just return an object literal

function newCodes(){
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        dCodes: dCodes, 
        dCodes2: dCodes2
    };  
}


var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
2
  • @SeanKinsey I like this solution. It may be useful for me. One question, should there be a need for a function in the return would every instance of result (result1 .. resultN) get its own copy of the function or would there be resuse of the function code? (I don't know how I could test for this.) TIA.
    – Karl
    Oct 29, 2012 at 16:28
  • Easy comprehendible answer. Understood it with just one look. Thank you Oct 12, 2022 at 7:10
60

Since ES6 you can do this

let newCodes = function() {  
    const dCodes = fg.codecsCodes.rs
    const dCodes2 = fg.codecsCodes2.rs
    return {dCodes, dCodes2}
};

let {dCodes, dCodes2} = newCodes()

Return expression {dCodes, dCodes2} is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}.

This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()

2
27

Ecmascript 6 includes "destructuring assignments" (as kangax mentioned) so in all browsers (not just Firefox) you'll be able to capture an array of values without having to make a named array or object for the sole purpose of capturing them.

//so to capture from this function
function myfunction()
{
 var n=0;var s=1;var w=2;var e=3;
 return [n,s,w,e];
}

//instead of having to make a named array or object like this
var IexistJusttoCapture = new Array();
IexistJusttoCapture = myfunction();
north=IexistJusttoCapture[0];
south=IexistJusttoCapture[1];
west=IexistJusttoCapture[2];
east=IexistJusttoCapture[3];

//you'll be able to just do this
[north, south, west, east] = myfunction(); 

You can try it out in Firefox already!

0
25

Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.

function fun1() {
  var x = 'a';
  var y = 'b';
  return { x, y, z: 'c' };
  // literally means { x: x, y: y, z: 'c' };
}

var { z, x, y } = fun1(); // order or full presence is not really important
// literally means var r = fun1(), x = r.x, y = r.y, z = r.z;
console.log(x, y, z);

This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.

But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.

2
  • That is not yet working on IE or Edge, just wanted to note. Jan 11, 2017 at 17:58
  • Been using this quite a bit... it's faster/smoother to use an array and avoid constructing an object if possible as shown by @user3015682.
    – dkloke
    Aug 9, 2017 at 15:26
23
function a(){
  var d = 2;
  var c = 3;
  var f = 4;
  return {d: d, c: c, f: f};
}

Then use

const {d, c, f} = a();

In new version:

function a(){
  var d = 2;
  var c = 3;
  var f = 4;
  return {d, c, f}
}
3
  • 2
    Then run the function again for each variable? That's not the best approach. Oct 22, 2015 at 20:18
  • Every time the interpreter meets a() it runs the function again. So, var f = a().f; var c = a().c; var d = a().d; will launch a() three times, which is prone to performance loss. The better approach would be var result = a(); var f = result.f; etc. Nov 15, 2015 at 13:06
  • 1
    ok for better performance, you can keep value to a variable and use it, for example var result=a(); and use value result.d or result.c and result.f , so just at one time run a() function.
    – Behnam
    Nov 16, 2015 at 6:25
13

A very common way to return multiple values in javascript is using an object literals, so something like:

const myFunction = () => {
  const firstName = "Alireza", 
        familyName = "Dezfoolian",
        age = 35;
  return { firstName, familyName, age};
}

and get the values like this:

myFunction().firstName; //Alireza
myFunction().familyName; //Dezfoolian
myFunction().age; //age

or even a shorter way:

const {firstName, familyName, age} = myFunction();

and get them individually like:

firstName; //Alireza
familyName; //Dezfoolian
age; //35
9

Other than returning an array or an object as others have recommended, you can also use a collector function (similar to the one found in The Little Schemer):

function a(collector){
  collector(12,13);
}

var x,y;
a(function(a,b){
  x=a;
  y=b;
});

I made a jsperf test to see which one of the three methods is faster. Array is fastest and collector is slowest.

http://jsperf.com/returning-multiple-values-2

1
  • Typically collector is called continuation and the technique is called CPS
    – ceving
    May 31, 2019 at 14:03
7

In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

becomes

var newCodes = function(fg, cb) {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    cb(null, dCodes, dCodes2);
};

:)

bam! This is simply another way of solving your problem.

6

You can also do:

function a(){
  var d=2;
  var c=3;
  var f=4;
  return {d:d,c:c,f:f}
}

const {d,c,f} = a()
0
6

Adding the missing important parts to make this question a complete resource, as this comes up in search results.

Object Destructuring

In object destructuring, you don't necessarily need to use the same key value as your variable name, you can assign a different variable name by defining it as below:

const newCodes = () => {  
    let dCodes = fg.codecsCodes.rs;
    let dCodes2 = fg.codecsCodes2.rs;
    return { dCodes, dCodes2 };
};

//destructuring
let { dCodes: code1, dCodes2: code2 } = newCodes();

//now it can be accessed by code1 & code2
console.log(code1, code2);

Array Destructuring

In array destructuring, you can skip the values you don't need.

const newCodes = () => {  
    //...
    return [ dCodes, dCodes2, dCodes3 ];
};

let [ code1, code2 ] = newCodes(); //first two items
let [ code1, ,code3 ] = newCodes(); //skip middle item, get first & last
let [ ,, code3 ] = newCodes(); //skip first two items, get last
let [ code1, ...rest ] = newCodes(); //first item, and others as an array

It's worth noticing that ...rest should always be at the end as it doesn't make any sense to destruct anything after everything else is aggregated to rest.

I hope this will add some value to this question :)

4

You can use "Object"

function newCodes(){
    var obj= new Object();
    obj.dCodes = fg.codecsCodes.rs;
    obj.dCodes2 = fg.codecsCodes2.rs;

    return obj;
}
1
  • 1
    This is the way to go for IE. Later use like: let obj = newCodes(); alert(obj.dCodes); Dec 23, 2019 at 13:16
3

I would suggest to use the latest destructuring assignment (But make sure it's supported in your environment)

var newCodes = function () {
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return {firstCodes: dCodes, secondCodes: dCodes2};
};
var {firstCodes, secondCodes} = newCodes()
2

All's correct. return logically processes from left to right and returns the last value.

function foo(){
    return 1,2,3;
}

>> foo()
>> 3
1
  • 1
    the , is an operator and can be used in any expression. There's nothing special about return here.
    – gman
    Dec 27, 2017 at 6:53
2

I know of two ways to do this: 1. Return as Array 2. Return as Object

Here's an example I found:

<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var arr = [dividend, divisor, quotient];
    return arr;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
</script>



<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var obj = {
        dividend: dividend,
        divisor: divisor,
        quotient: quotient
    };
    return obj;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all.dividend); // 0utputs: 10
alert(all.divisor); // 0utputs: 2
alert(all.quotient); // 0utputs: 5
</script>
1

Few Days ago i had the similar requirement of getting multiple return values from a function that i created.

From many return values , i needed it to return only specific value for a given condition and then other return value corresponding to other condition.


Here is the Example of how i did that :

Function:

function myTodayDate(){
    var today = new Date();
    var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
    var myTodayObj = 
    {
        myDate : today.getDate(),
        myDay : day[today.getDay()],
        myMonth : month[today.getMonth()],
        year : today.getFullYear()
    }
    return myTodayObj;
}

Getting Required return value from object returned by function :

var todayDate = myTodayDate().myDate;
var todayDay = myTodayDate().myDay;
var todayMonth = myTodayDate().myMonth;
var todayYear = myTodayDate().year;

The whole point of answering this question is to share this approach of getting Date in good format. Hope it helped you :)

1

I am nothing adding new here but another alternate way.

 var newCodes = function() {
     var dCodes = fg.codecsCodes.rs;
     var dCodes2 = fg.codecsCodes2.rs;
     let [...val] = [dCodes,dCodes2];
     return [...val];
 };
1

Well we can not exactly do what your trying. But something likely to below can be done.

function multiReturnValues(){
    return {x:10,y:20};
}

Then when calling the method

const {x,y} = multiReturnValues();

console.log(x) ---> 10
console.log(y) ---> 20
0

It is possible to return a string with many values and variables using the template literals `${}`

like:

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return `${dCodes}, ${dCodes2}`;
};

It's short and simple.

Not the answer you're looking for? Browse other questions tagged or ask your own question.