Tux9000
Tux9000

Reputation: 155

How to return multiple values ​with a function?

In what way could I make the function return 3 values ​​to me so that those 3 values ​​would serve as input parameters for another function (as if it were a callback --which in fact, I think it is--)?

Until now, try the following (although it did not work):

var resultado;
function num_2(repet){
	for (var i = 0; i > repet-1; i++) {
		if (i>=1) {
			return i + ", ";
		}else{
			return i;
		}
	}
}


function sumarr(a,b,c){
	if (a!="" && a!=null) {
		resultado = a+b+c;
		return "\n" + "resul: " + resultado + '\n' + "1: " +
		a + '\n' + "2: " + b + '\n' + "3: " + c + '\n' + '\n';
	}else{
		return "noting";
	}
}
console.log("\n" + "callback 2: " + sumarr(num_2(3)));

Upvotes: 2

Views: 6667

Answers (4)

Maheer Ali
Maheer Ali

Reputation: 36564

You can return an array from the first function and pass each element to another other function as independent argument using Spread Operator.

var resultado;
function num_2(repet){
  return [...Array(repet)].map((x,i) => i)
}
function sumarr(a,b,c){
	return a + b + c
}
console.log("\n" + "callback 2: " + sumarr(...num_2(3)))

If its hard for you to understand the first function so its same as

function num_2(repet){
  let res = [];
  for(let i = 0;i<repet;i++){
     res.push(i)
  }
  return res;
}

Upvotes: 4

Dave Anderson
Dave Anderson

Reputation: 12294

You have two options; return a JSON object, return an array.

Returning a JSON object you can name the properties then modify the second function to accept the object and access the properties;

var input = function() { 
   return { 
     a: 1, 
     b: 2 
   }; 
}
   
var output = function(obj) { 
   console.log(obj.a);
   console.log(obj.b);
}

output(input());

Returning an array and using that as the arguments to call the function with apply() or with spread syntax

var input = function() { 
   return [1, 2]; 
}
  
var output = function(a, b) { 
   console.log(a);
   console.log(b);
}

output.apply(this, input());

output(...input());

These all have the same result printing the following in the console;

1
2

Upvotes: 3

Mister Jojo
Mister Jojo

Reputation: 22320

with JS object :

var Vals = Return3Values();

console.log( Vals.a, Vals.b, Vals.c );

function Return3Values()
{
 return {a:5, b:'hello', c:15 }
}

Upvotes: 2

BlueWater86
BlueWater86

Reputation: 1817

If you are able to use the latest JS features, you can use Destructuring Assignment in your functions to solve this and clean up your code.

function logLotsOfThings({thing1, thing2, thing3}) {
  console.log(thing1, thing2, thing3)
}

function getLotsOfThings() {
  return {
    thing1: "I am thing 1",
    thing2: "I am thing 2",
    thing3: "I am thing 3"
  }
}

logLotsOfThings(getLotsOfThings())

Upvotes: 1

Related Questions