Back to all posts

Function Parameters


In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly value. This is exactly what default parameters do.

Back in time coders are manually test parameter value in the body of the function and assign a value if they are undefined.

Example for check functions parameters are defined or not
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a * b;
}

console.log(multiply(5)); // 5

Default parameters

with default parameters a manual check in the function body is no longer necessary. You can put 1 as the default value for b in the function head:

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5)); // 5

Reset Parameters

In JavaScript, Reset parameters allows a function to accept an indefinite number of arguments as an array. this provides a way to represent variadic functions in JavaScript. The reset parameter is indicated by three dots (`…`) before the parameter’s name.

Syntax

Here’s a basic example of how you might define a function with reset parameters:

function fn(a, b, ...args) {
   //...
}

Example

function multiply(multiplier, ...theArgs) {
  return theArgs.map((x) => multiplier * x);
}

const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]