I was trying to write some javascript function and realised that
function testFunction(input_1, input_2, input_3) { alert("alert"); }
however when i call the function like this:
<input type="button" value="click" onclick="testFunction("1", "2")">
why will it still work even with just two parameters?
The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit.
A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.
The typeof operator returns a string which indicates the type of the unevaluated operand. Both of these operators provide a Boolean result. This result can be compared using the IF statement to check if the object type is "Function'.
You can call a Javascript function with any number of parameters, regardless of the function's definition.
Any named parameters that weren't passed will be undefined
.
Extra parameters can be accessed through the arguments
array-like object.
It doesn't actually matter how many parameters you are providing. the function interprets them and creates the arguments
object (which acts as an array of parameters). Here's an example:
function sum(){ if(arguments.length === 0) return 0; if(arguments.length === 1) return arguments[0]; return arguments[0] + sum.apply(this, [].slice.call(arguments, 1)); }
It's not the most efficient solution, but it provides a short peak at how functions can handle arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With