JavaScript Function Parameters
A JavaScript function
doesn't check the values of its parameters (arguments).
Function Parameters and Arguments
In the previous part of this guide, you discovered that functions can include parameters:
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are the names mentioned in the function definition.
Function arguments are the actual values that get sent to (and received by)a function.
Parameter Rules
JavaScript functions don't mention the data types for parameters in their definitions.
JavaScript functions do not check the types of the arguments they receive.
JavaScript functions do not verify the number of arguments they receive.
Default Parameters
If a function is used without providing all the required information (fewer than specified), the absent values are assigned the value undefined
.
At times, it's fine, but in some cases, it's preferable to set a default value for the parameter.
Default Parameter Values
ES6 lets you set default values for function parameters.
Function Rest Parameter
The rest parameter (…) enables a function to handle a variable number of arguments in the form of an array.
The Arguments Object
In JavaScript, there is a special object called the arguments object that comes with functions.
The argument object holds a list of the values used when the function was called.
You can easily employ a function to locate the highest value in a list of numbers using this method:
Make a function that adds up all the given input values.
If you use more arguments than declared when calling a function, you can access these extra arguments using the arguments object.
Arguments are Passed by Value
In a function call, the parameters refer to the arguments of the function.
In JavaScript, arguments are transferred by value. This means that a function receives only the values of the arguments, not their specific locations.
If a function alters the value of an argument, it does not affect the original value of the parameter.
Modifications to inputs are not apparent outside the function.
Objects are Passed by Reference
In JavaScript, values represent object references.
Due to this, objects will act as if they are being handled as a reference:
When a function alters a property of an object, it modifies the original value.
Modifying object properties can be seen outside the function.