0

If i have a function that receives a call like

function car_total(y) {

final_total(y);
}


function toy_total(x) {

final_total(x);
}

How can I make a function that computes both totals if they exist but can only receive 1 parameter and not throw an error, is this possible?

function final_total(x,y) {
//if passed just x
sum = x ;
//if passed just y 
sum = y;
//if passed x, y 
sum = x + y ; 

}
Amanda Sky
  • 153
  • 1
  • 2
  • 9
  • 1
    this should help you out, it's a previous post: http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function – Jay Blanchard Nov 21 '12 at 20:05

3 Answers3

6

You can pass only one argument, but with only one argument that argument must be x; as there's no way (without passing an object) of determining which variable you 'meant' to pass in. Therefore the first variable recieved will always be x, the second y, that said, though, I'd suggest:

function final_total(x,y) {
    return y ? x + y : x;
}

And, in the presence of only one passed-in argument this function returns that single value or, given two variables, returns the sum of those two. So this does do as you want, even if there's no way to ascertain whether x or y was passed-in.

If, however, you must explicitly pass in either x or y (for some reason):

function final_total(values) {
    var x = values.x || 0,
        y = values.y || 0;
    return x + y;
}

var variableName1 = final_total({x : 23, y : 4});
console.log(variableName1);
// 27

var variableName2 = final_total({y : 4});
console.log(variableName2);
// 4

var variableName3 = final_total({x : 23});
console.log(variableName3);
// 23​

JS Fiddle demo.

David Thomas
  • 240,457
  • 50
  • 366
  • 401
0

You could define the function like you have it, and then check if either of the arguments are null. The downside is you would have to make sure to put the null in the right place when you call it.

function final_total(x,y) {

    if(x && y) sum = x + y;
    else if (x) sum = x;
    else if (y) sum = y; 

}
WildCrustacean
  • 5,806
  • 1
  • 30
  • 41
0
var final_total = function(x,y) { return x+(y||0); };
neiker
  • 8,784
  • 4
  • 28
  • 32
  • 1
    Returns `NaN` when no arguments are provided, not sure if the OP is concerned about the output in this case. – Asad Saeeduddin Nov 21 '12 at 20:15
  • She asked to use it with 1 parameter.. if you want thats works without arguments use: var final_total = function(x,y) { return (x||0)+(y||0); }; – neiker Nov 21 '12 at 20:34