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.