Wenz
Wenz

Reputation: 97

Javascript: Passing arguments from multiple functions to 1 function

I have several functions that evaluate some variables and come up with a result

For example:

function first(){
   //variable declarations
   var result1 = a+b
}

function two(){
   //variable declarations
   var result2 =c+d 
}

I want to pass both of those results to another function

function three( result1, result2 ) {
   var finalResult = result1 + result2;
}

My question is where do I call function 3 from. because in reality I have about 10 functions with results I need to pass. Do I put three(result#) at the end of each???

thankyou

Upvotes: 2

Views: 1724

Answers (5)

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

A better way is to pass an object. It will make sure if you want to put more details, you wont have to add more arguments in the function and make it more readable.

function first(){
    return "value of one";
} 

function second(){
    return "value of two";
}


function three(data){
    var finalResult = data.first + data.second;
}

ANd call it like:

var data = {};
data.first = first();
data.second = second();

three(data);

Upvotes: 1

cjds
cjds

Reputation: 8426

Don't bother with the global results, i.e. result1,result2 etc. Just return the data and call 3 when ready with all

function first(){
 return a+b;
} 

function two(){
  return c+d;
}

function three(){
     return (first() + two());
 }

Upvotes: 1

Tepken Vannkorn
Tepken Vannkorn

Reputation: 9723

function one( a, b ) {
   var result1 = a + b;
   return result1;
}

function two( c, d ) {
   var result2 = c + d;
   return result2;
}

function three( a, b ) {
   var finalResult = a + b;
   return finalResult;
}

To call it use three( one(), two() );

Upvotes: 0

Travis J
Travis J

Reputation: 82357

Here is one approach you could take, although the question is a little vague.

function first(){
 return a+b;
} 

function two(){
 return c+d;
}

function three(){
 var finalResult = first() + two();
}

Or, if you didn't want the value in a function, you could do this:

<script>
 var results = first() + two();
</script>

Upvotes: 1

Rasmus
Rasmus

Reputation: 1685

function first() {
    return a + b;
}

function two() {
    return c + d;
}

function three(result1, result2) {
    return result1 + result2;
}

Call it:

var finalResult = three(first(), two());

Upvotes: 1

Related Questions