2

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

5
  • What gives you undefined ? What do you want third() to do ? Commented Jan 19, 2017 at 9:36
  • a and b are both defined after you execute third(). Commented Jan 19, 2017 at 9:37
  • 3
    Your functions are returning a value as is correct but you are not doing anything with the values. What do you want to do with the values ? Commented Jan 19, 2017 at 9:38
  • If you want third to return something, then you need write a return statement in third. Commented Jan 19, 2017 at 9:38
  • var third = _ => [first(),second()]; could be a start. Commented Jan 19, 2017 at 9:47

3 Answers 3

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.