JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
Function Parameters
A JavaScript function does not check the parameter values (arguments).
Function Parameters and Arguments
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are the names listed in the function definition
Function arguments are the real values passed to (and received by) the function.
Parameter Rules
JavaScript functions do not specify data types for parameters.
JavaScript functions do not perform checks on the passed arguments.
JavaScript functions do not check the number of arguments retrieved.
Default Parameters
If a function is called without any arguments (less than declared), the missing values are set to undefined.
At times, it is acceptable, but it is better to assign a default value to the parameter:
Example
<!DOCTYPE html>
<html>
<body>
<p>Setting a default value to a function parameter.</p>
<p id=”demo”></p>
<script>
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
return x * y;
}
document.getElementById(“demo”).innerHTML = myFunction(4);
</script>
</body>
</html>
Output
Setting a default value to a function parameter.
The Arguments Object
JavaScript functions consist of a built-in object called the arguments to object.
The argument object has an array of the arguments used when the function was called (invoked).
You can simply use a function to find (for instance) the highest value in a list of numbers.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Finding the largest number.</p>
<p id=”demo”></p>
<script>
function findMax() {
let max = -Infinity;
for(let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
document.getElementById(“demo”).innerHTML = findMax(4, 5, 6);
</script>
</body>
</html>
Output
JavaScript Functions
Finding the largest number.
6
Arguments are Passed by Value
- The parameters, in a function call, are the function’s arguments.
- JavaScript arguments are passed through value.
- If a function changes an argument’s value, it does not alter the parameter’s original value.
- Any changes to arguments are not reflected outside the function.
Objects are Passed by Reference
- In JavaScript, object references are values.
- Because of this, objects will behave as if they are passed by reference:
- If a function changes an object’s property, it alters the original value.
- Any changes to object properties are reflected outside the function.