HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Parameters

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.


Default Parameters (ES6)

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

Function Rest Parameter (...)

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

The Arguments Object

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;
}

Pass by Value vs. Reference

Pass by Value

Primitive parameters (like numbers) are passed by value. Changing the parameter inside the function does not change the original variable.

Pass by Reference

Objects and Arrays are passed by reference. If you change an object property inside a function, the original object is changed.


Key Points to Remember

  • Parameters are in the definition; Arguments are the real values
  • Use Default Parameters to handle missing values safely
  • The Rest Parameter (...) collects multiple arguments into an array
  • JavaScript doesn't check the number of arguments (missing ones are undefined)
  • Primitives are safe from modification (Pass by Value)
  • Objects are mutable when pass to functions (Pass by Reference)