JavaScript Function Parameters

JavaScript functions do not check the value of the parameter.

Parameters and Arguments of the function

In the previous tutorial, we have learned about the explicit parameters of a function:


functionName(parameter1, parameter2, parameter3) { 

code to be executed 


The function's explicit parameters are listed when the function is defined.

The function implicit parameter is passed to the function the real value when the function is called.

Parameter rules

JavaScript functions do not specify a data type when defining explicit parameters.

JavaScript functions do not perform type detection on implicit parameters.

JavaScript function does not detect the number of implicit parameters.

Parameter Defaults

In ES5, if a function does not provide an implicit parameter when it is called, the parameter is set to: undefined

Sometimes this is acceptable, but it is recommended to set a default value for the parameter:


function myFunction(x, y) {
    if (y === undefined) {
          y = 0;

Or, the easier way:


function myFunction (x, y = 10) { //y is 10 if not passed or undefined return x + y; } myFunction (0, 2) //output 2 myFunction (5); //output 15, default value of y parameter

arguments object

JavaScript functions have a built-in object arguments Object.

The argument object contains an array of arguments for the function call.

In this way, you can easily find the value of the largest parameter:

x = findMax(1, 123, 500, 115, 44, 88); function findMax() { var i, max = arguments[0]; if(arguments.length < 2) return max; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }

Or create a function to count the sum of all values:

x = sumAll(1, 123, 500, 115, 44, 88); function sumAll() { var i, sum = 0; for (i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; }

Pass parameters by value

The parameters called in the function are implicit parameters of the function.

JavaScript implicit parameters are passed by value: functions just get values.

If a function modifies the value of a parameter, it does not modify the initial value of the explicit parameter (defined outside the function).

Changes to implicit parameters are not visible outside the function.

Passing parameters through objects

In JavaScript, you can reference the value of an object.

So we modify the object's properties inside the function to modify its initial value.

Modifying object properties can be applied outside the function (global variables).

Modified object properties are visible outside the function.