Dam
Dam

Reputation: 21

Javascript: return multiple values from different functions

I am trying to return multiple values from different functions. The starting point is a bidimensional array. An example of the code is:

var items = [[0,1],[1,2],[0,2]];
var a;
var b;

function first() {
a = items[Math.floor(Math.random() * items.length)];
return a;
}

function second() {
b = a[Math.floor(Math.random() * 2)];
return b;
}

function third (){
  first();
  second();
}

third();

If I write the code outside the functions, everything works fine. When I use functions and replace return with console.log, it works. If I use functions and return (as in the code reported above), it gives me undefined. I didn't find solutions. Why the code isn't working?

Thanks in advance

Upvotes: 2

Views: 239

Answers (3)

Simone Sanfratello
Simone Sanfratello

Reputation: 1620

Maybe you want something like

function third (){
  return {a: first(), b: second()};
}

then

var t = third()
console.log(t.a, t.b)

or if you're running on ES6

var {a,b} = third()
console.log(a, b)

see Destructuring assignment for further details

Upvotes: 1

fatema
fatema

Reputation: 211

If you are declaring variable a and b outside function(like in your code) than there is no need to return the values. a and b will get defined. But if you are not declaring it outside, then store the return values in array variable.

var items = [[0,1],[1,2],[0,2]];

function first() {
a = items[Math.floor(Math.random() * items.length)];
return a;
}

function second() {
b = a[Math.floor(Math.random() * 2)];
return b;
}

function third (){
var a = first();
var b = second();
var arr  = [];
arr.push(a);
arr.push(b);
return arr 
}

var t = third();
console.log(t[0], t[1]);

Upvotes: 2

strwoc
strwoc

Reputation: 533

If you want third to return values, add a return in it.

function third (){
  var a = [];
  a.push(first())
  a.push(second())
  return a;
}

Upvotes: 1

Related Questions