Skip to content Skip to sidebar Skip to footer

Optional Arguments In JavaScript

Why doesn't this function throw an error if the remaining arguments are missing? showStatistics('Mark Teixeira', 'New York Yankees', '1st Base'); Here is a the function defined: f

Solution 1:

Any argument that is not passed appears as undefined inside the function. In JavaScript there is no method overloading.


Solution 2:

Remember that "arrays" in JS area actually associative. So the 2, 3, ... that you put in as indexed area really just hash keys. You could also check the value of arguments[54876]. That would not fail, but return to you undefined. So even though you're thinking of your parameter array as having only three valid indices and anything else giving you something along the lines of "index out of bounds", you really have three valid entries and lookup with any other keys don't fail, but give you undefined.


Solution 3:

The parameters which aren't passed a value are set to undefined, which is not an error unless you try to do something with it that cannot be done with undefined. The only thing you are doing is checking if typeof undefined === 'number', which simply returns false, but does not throw an error.


Post a Comment for "Optional Arguments In JavaScript"