Another unique aspect of JavaScript functions is that you can pass any number of parameters to any function without causing an error. That’s because function parameters are actually stored as an array-like structure called arguments.
On the other hand, JavaScript doesn’t ignore the named parameters
of a function either. The number of arguments a function expects is stored
on the function’s length property. Remember, a function is actually just an
object, so it can have properties. The length property indicates the function’s arity, or the number of parameters it expects. Knowing the function’s
arity is important in JavaScript because functions won’t throw an error if
you pass in too many or too few parameters
(see next code running here -> https://playcode.io/664865)
function reflect(value) { return value; } console.log(reflect("Hi!")); // "Hi!" console.log(reflect("Hi!", 25)); // "Hi!" console.log(reflect.length); // 1 reflect = function() { return arguments[0]; }; console.log(reflect("Hi!")); // "Hi!" console.log(reflect("Hi!", 25)); // "Hi!" console.log(reflect.length); // 0
The version that uses the arguments object can be confusing because there are no named arguments, and you must read the body of the function to determine if arguments are used. That is why many developers prefer to avoid using arguments unless necessary.
Sometimes, however, using arguments is actually more effective than naming parameters
function sum() { var result = 0, i = 0, len = arguments.length; while (i < len) { result += arguments[i]; i++; } return result; } console.log(sum(1, 2)); // 3 console.log(sum(3, 4, 5, 6)); // 18 console.log(sum(50)); // 50 console.log(sum()); //
THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT. Copyright © 2014 by Nicholas C. Zakas