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 ;
}
-
1this should help you out, it's a previous post: stackoverflow.com/questions/2141520/…Jay Blanchard– Jay Blanchard2012年11月21日 20:05:42 +00:00Commented Nov 21, 2012 at 20:05
3 Answers 3
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
Comments
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;
}
4 Comments
x will be undefined, and anyway this is the most possible verbose way.x will be undefined? Unless it gets called with no arguments, x should have something. I know this is the most verbose way, but I figured I'd post it anyway. Sometimes verbose is good at first.var final_total = function(x,y) { return x+(y||0); };