Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on Javascript Function Parameters

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?

like image 861
simplified. Avatar asked Jun 22 '11 20:06

simplified.


People also ask

What are parameters in JavaScript functions?

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.

How many parameters can be passed to a function in JavaScript?

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.

Can a JavaScript function have parameters?

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.

How do you check if a parameter is a function in JavaScript?

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'.


2 Answers

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.

like image 98
SLaks Avatar answered Oct 14 '22 07:10

SLaks


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.

like image 38
gion_13 Avatar answered Oct 14 '22 06:10

gion_13