Here we have a discussion about the difference between defined parameters and actual arguments passed.
When looking at a defined function, you can determine the number of parameters specified in the function definition using fn.length
:
function speak(message, volume) {
// code goes here
}
console.log(speak.length); // displays 2 since two parameters are defined in the function
On the other hand, within a function, you can find out how many arguments were actually passed during a specific invocation with arguments.length
. For instance, if a function is designed to potentially accept an optional callback as the last argument:
function speak(message, volume, callback) {
console.log(arguments.length); // shows the actual number of passed arguments
}
speak("hi", 100); // will output 2 for the number of arguments passed
speak("hi", 100, function() { // will display 3 arguments passed
console.log("speaking is complete");
});