Parameters & Arguments

Understanding function inputs.

Examples

Default Parameters

Using default values for parameters.

function myFunction(x, y = 10) {
  return x + y;
}
console.log(myFunction(5)); // 15
console.log(myFunction(5, 2)); // 7

Arguments Object

Accessing function arguments using the arguments object.

function findMax() {
  let max = -Infinity;
  for (let i = 0; i < arguments.length; i++) {
    if (arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}
console.log(findMax(4, 5, 6, 1)); // 6

Rest Parameter

Using the rest parameter (...) to handle an indefinite number of arguments.

function sum(...args) {
  let sum = 0;
  for (let arg of args) sum += arg;
  return sum;
}
console.log(sum(4, 9, 16, 25, 29, 100, 66, 77));

Test Your Knowledge

JavaScript Quiz

No quiz available for this topic yet.