JavaScript Function Parameters
- Previous Page JS Function Definition
- Next Page JS Function Calls
JavaScript functiondo not perform any checks on the parameter values.
function parameters
At an earlier time in this tutorial, you have learned that functions can haveParameters:
functionName(parameter1, parameter2, parameter3) { code to be executed }
function parametersrefers to theName.
function argumentsrefers to the actualValue.
Parameter rules
The definition of JavaScript function does not specify the data type of the parameters.
JavaScript functions do not perform type checking on the arguments passed.
JavaScript functions do not check the number of arguments received.
Parameter defaults
If the parameters are calledParameters are omittedIf the number of parameters is less than the declared number), the missing values are set to:undefined.
Sometimes this is acceptable, but sometimes it is better to specify default values for the parameters:
Example
function myFunction(x, y) { if (y === undefined) { y = 0; } }
If the number of parameters in the function callToo many parametersIf the number of parameters exceeds the declared number), The arguments objectto access these parameters.
The arguments object
JavaScript functions have a built-in object named arguments.
The arguments object contains an array of parameters used when the function is called.
Thus, you can simply use the function to find the highest value in a list of numbers (for example):
Example
x = findMax(1, 123, 500, 115, 44, 88); function findMax() { var i; var max = -Infinity; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }
Or create a function to sum all input values:
Example
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; }
Parameters are passed by value
The parameters (parameter) in the function call are the arguments (argument) of the function.
JavaScript parameters are passed throughValuePassing: The function knows the value, not the position of the parameters.
If the function changes the value of the parameters, it does not change the original value of the parameters.
Changes to parameters are not visible outside the function.
Objects are passed by reference
In JavaScript, object references are values.
Therefore, objects behave as if they were passed throughReferenceTo pass:
If the function changes object properties, it also changes the original value.
Changes to object properties are visible outside the function.
- Previous Page JS Function Definition
- Next Page JS Function Calls