A JavaScript function does not perform any check on parameter values (arguments). JavaScript parameters are variables listed in the function definition, while arguments are the actual values passed to the function.
ES6 allows function parameters to have default values. If an argument is not provided during invocation, the default value will be used.
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
console.log(myFunction(5)); // Result: 15
The rest parameter allows a function to treat an indefinite number of arguments as an array. This is very useful when you don't know how many arguments will be passed.
function sum(...args) {
let total = 0;
for (let arg of args) total += arg;
return total;
}
console.log(sum(1, 2, 3, 4, 10)); // Result: 20
Before ES6, JavaScript functions had a built-in object called the
arguments object. It contains an array of the arguments used
when the function was called.
function findMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) max = arguments[i];
}
return max;
}
Primitive parameters (like numbers) are passed by value. Changing the parameter inside the function does not change the original variable.
Objects and Arrays are passed by reference. If you change an object property inside a function, the original object is changed.
undefined)