JavaScript – Quick Tip of the Day

Yesterday I thrilled you with the gory details of the arity property of JS functions, which is basically an argument count. Every function (even the ones you dream up) has an arity property, which you can inspect with code like that shown below. (This is the same code from yesterday.) The thing I forgot to mention yesterday is that every function also has an arguments array property, although frankly that should be obvious from looking at the code example. Here is that code again:



function SumOfAllArgs(){argCount = SumOfAllArgs.arity;var sum = 0;
for (i = 0 ; i < argCount; i++ ) sum += SumOfAllArgs.arguments[i];
app.alert('arity = ' + SumOfAllArgs.arity +', and return value is ' + sum);
return sum;}

The function was declared as having no arguments, and yet JavaScript doesn’t complain at

all if you pass it arguments, in any quantity you desire. Try it yourself! Put the

foregoing code inside a PDF form and call the function with a handful of numeric arguments.

See what pops up on the screen when app.alert() executes.

Yesterday I asked you to guess what happens if you pass an argument of ‘true’ in the

above function. The answer is, arity becomes 1 and the return value is 1. I also asked you

to think about what might happen if (in a fit of schizophrenia) you were to pass in an

argument value of ‘test()’ (without quotes) to the above function. Answer: It executes

twice. The first time is with a null argument, hence arity == 1 and return == 0; the 2nd

time, arity == 1 and return == 1.

You May Also Like

About the Author: Kas Thomas

Leave a Reply