If the insistence on sending fewer than the defined number of function parameters is still desired, a proposed solution would be to range check the arguments as any prudent developer should do.
function foo( x, y ) {
var numParams = arguments.length;
if( typeof( y ) !== "number" ) { numParams = 1; }
if( typeof( x ) !== "number" ) { numParams = 0; }
for( var i=0; i<numParams; i++ ) {
console.log( arguments[ i ] );
}
}
The above solution, unlike the #3 work around allows for the design requirement of two parameters x and y in function foo( x, y ) and the ability to use the arguments object to iterate over the values passed, even when less than defined are supplied by the caller, not producing an error as what was desired in post #1.
>foo(4,5)
4
5
>foo(4)
4
>foo(4,5,6,7)
4
5
6
7
// 'undefined' is a normal return response when a function doesn't specify a return value. note the supplied leading equals sign, that is not part of the function and supplied by the Espruino response as the function doesn't definitively specify a return value
>foo()
=undefined
The function definition containing two parameters is to the original poster's specification, along with the iteration over the arguments list without error.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Sun 2019.08.18
Proposed Solution
If the insistence on sending fewer than the defined number of function parameters is still desired, a proposed solution would be to range check the arguments as any prudent developer should do.
We'll perform that task with the
typeof
operator.The above solution, unlike the #3 work around allows for the design requirement of two parameters x and y in function
foo( x, y )
and the ability to use thearguments
object to iterate over the values passed, even when less than defined are supplied by the caller, not producing an error as what was desired in post #1.The function definition containing two parameters is to the original poster's specification, along with the iteration over the arguments list without error.