JavaScript function allow you group together some code, give this code block a name, and reuse it later, addressing it by name.
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]) { //code to be executed }
arg1, arg2, ...argN are arguments which are optional.
Let's see an example.
function sum(a, b) { var c = a + b; return c; }
What makes up a function?
To call(Invoke) a function simply use its name followed by any parameters in parentheses.
Call the function sum(), by passing two parameters and assign value returned by the function to a variable result.
var result = sum(1, 2); result; // 3
A function may not require any parameters. You can also define a function, and specify what parameters the function expects to receive when it is called.
If you forget to pass parameters to a function which expects to receive when it is called, JavaScript will assign the value undefined to the ones you skipped.
In the below example, the function call returns NaN because it tries to sum 1 and undefined:
sum(1) // NaN
If you pass more parameters than the function expects, the extra parameters will be silently ignored.
sum(1, 2, 3, 4, 5) //3
You can create functions that are flexible about the number of parameters they accept. An arguments array is created automatically inside each function.
Here's a function that simply returns whatever parameters are passed to it.
function args() { return arguments; } args(); //[]
args( 1, 2, 3, 4, true, 'ninja'); [1, 2, 3, 4, true, "ninja"]
By using the arguments array you can improve the sum() function to accept any number of parameters and add them all up.
function sumOnSteroids() { var i, res = 0; var number_of_params = arguments.length; for (i = 0; i & lt; number_of_params; i++) { res += arguments[i]; } return res; }
Arguments is not an array, but an array-like object. The expression arguments.length returns the number of parameters passed when the function was called.
If you test this function by calling it with a different number of parameters (or even no parameters at all), you can verify that it works as expected:
sumOnSteroids(1, 1, 1); 3 sumOnSteroids(1, 2, 3, 4); 10 sumOnSteroids(1, 2, 3, 4, 4, 3, 2, 1); 20 sumOnSteroids(5); 5 sumOnSteroids(); 0