Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Advance Javascript Module...
  5. Rest/Spread Operators and Default Function Parameters

Rest/Spread Operators and Default Function Parameters

Rest Operators

The introduction of the rest parameter in JavaScript enables the capturing of multiple function arguments as an array. This proves valuable when dealing with a varying number of arguments and the need to handle them as a unified collection.

Syntax

The rest parameter is denoted by three dots (`…`) followed by a parameter name. This parameter gathers all the remaining arguments passed to a function as an array

function myFunction(...args) {
    // 'args' is an array containing all arguments passed
}

${expressions}`

  • ‘myFunction’ is the name of the function
  • ‘…args’ is the rest parameter.
    • Inside the function, …args is treated as like array that holds all the additional arguments passed to the function.

The rest parameter can be used like any other array within the function. It contains all the arguments beyond the ones explicitly defined as individual parameters.

Restrictions:

  • More than one rest parameter is not allowed
  • A rest parameter must always come last.

Example

Sum of the elements

function sum(...numbers) {
  let total = 0;
  for (let number of numbers) {
    total += number;
  }
  return total;
}

console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40));

In the below example, the parameters are parsed and resolved via rest functionality. This outputs,

Output

Combining Rest Parameter with Regular Parameter

In a function declaration, regular parameters can be used alongside the rest parameter, but it’s essential to ensure that the rest parameter appears after all the regular parameters.

A rest parameter gathers all parameters following the first one and stores them in an array. Subsequently, each value in this array is multiplied by the initial parameter, and the resulting array is returned.

function multiply(multiplier, ...arg) {
  return arg.map((element) => multiplier * element);
}

const result = multiply(2, 5, 10, 15);
console.log(result);

Output

Enforcing a certain number of parameters via a rest parameter

Rest parameter can be used to enforce a certain number of arguments. Consider, the below example,

function sum_req_args(...numbers) {
  const req_arg_count = 3; // Change this to the number of required arguments you want.

  if (numbers.length !== req_arg_count) {
    throw new Error(`Exactly ${req_arg_count} arguments are required.`);
  }

  const result = numbers.reduce((total, num) => total + num, 0);
  return result;
}

try {
  const result = sum_req_args(2, 3, 4); // This will work with 3 arguments.
  console.log("Result:", result);
} catch (error) {
  console.error("Error:", error.message);
}

try {
  const result = sum_req_args(2, 3); // This will throw an error.
  console.log("Result:", result);
} catch (error) {
  console.error("Error:", error.message);
}
  • A function named sum_req_args that uses a rest parameter …numbers to accept any number of arguments as an array is defined. The purpose of this function is to calculate the sum of these numbers.
  • Declare a constant variable named req_arg_count and assign it the value of 3. This value can be adjusted to specify the desired number of required arguments for this function.
  • The code assesses whether the length of the `numbers` array, which holds the provided arguments, doesn’t correspond to the value stored in `req_arg_count`. When there’s a mismatch, it signifies that the function was invoked with an incorrect number of arguments.
  • If this condition is met (indicating an argument count that doesn’t align with expectations), an error is thrown, featuring an error message specifying the precise count of necessary arguments.
  • A try…catch block is used to call the sum_req_args function with different sets of arguments.
  • `throw`: This is a JavaScript keyword used to explicitly throw an exception. When `throw` is used, it stops the normal execution of the code and transfers control to the nearest enclosing `catch` block, or if there isn’t one, it terminates the script.
  • new Error()`: This part of the statement creates a new instance of the built-in `Error` object. The `Error` object is a standard JavaScript object that represents an error or an exception. This is used to create instances of `Error` to capture and describe errors in the code.
  • `Exactly ${req_arg_count} arguments are required.“: This is a template literal. Template literals are enclosed in backticks (“ ` “) and allow to embed expressions within `${}`. In this case, `${req_arg_count}` is an expression that evaluates to the value of the `req_arg_count` variable.

when this line of code is executed:

  • It creates a new `Error` object with a custom error message that says “Exactly X arguments are required,” where `X` is the value of the `req_arg_count` variable.
  • Then, it throws this error, which can be caught and handled by a surrounding `catch` block or, if not caught, will result in the script terminating with an error message.
  • The purpose of this line is to provide informative error messages when the function is called with an incorrect number of arguments, making it easier to understand what went wrong in the code.

Empty Rest Parameter

If no arguments are passed to a function that uses a rest parameter, the rest parameter will simply be an empty array.

function myFunction(...args) {
  console.log(args);
}

myFunction();

Output

Rest Parameter vs Arguments Object

The rest parameter is similar to the `arguments` object, but it has some advantages. Rest parameters are actual arrays, so you can use array methods and properties directly. The `arguments` object is an array-like object but array methods cannot be applied on that.

function example(...args) {
  console.log(args);
  console.log(arguments);
}

example("Cat", "Dog", "Rat");

Rest Parameter with arrays – Example

const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

Rest Parameter with array of objects

The rest parameter with objects  allows to collect all the remaining properties of an object into a new object. It provides a convenient way to destructure objects while still retaining access to the properties didn’t explicitly extract. The working is given as:

ØDestructuring: When object destructuring is used, one must  specify which properties to extract from an object and assign them to variables. Any properties not explicitly mentioned are typically left untouched.

ØRest Parameter: By using the rest parameter syntax (usually denoted by three dots `…` followed by a variable name), one can collect all the properties that were not explicitly destructured into a new object. This object contains the remaining properties.

ØUsage: The rest parameter is especially useful to access and work with some properties immediately while keeping others for later use or for further processing.

Rest Parameter with objects

const person = { name: "Rajalakshmi", age: 30, city: "Chennai" };
const { name, ...info } = person;

console.log(name); // 'Rajalakshmi'
console.log(info); // { age: 30, city: 'Chennai' }
console.log(info.age);

Spread Operator for Arrays

The spread operator is another powerful feature introduced in ES6, and it works in a way as related to rest parameters. It’s denoted by three dots (`…`) as well, but its purpose is to split an array or object into individual elements or properties.

When used with arrays, the spread operator can be used to create a new array by spreading the element of an existing array. The spread operator can be used to split an array into individual elements.

const numbers = [1, 2, 3];
const expandedNumbers = [...numbers, 4, 5];

console.log(expandedNumbers); // Outputs: [1, 2, 3, 4, 5]

Output

Spread Operators – Meging the array (concatenation)

The spread operator can be used to merge multiple arrays into one

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];

console.log(mergedArray); // Outputs: [1, 2, 3, 4, 5, 6]

Output

Clone the array

const arr1 = [10, 20, 30];
const arr2 = [...arr1];

console.log("After copying  arr2:", arr2);
arr2.push(40);
console.log("After Inserting 40 in arr2 : ", arr2);
console.log("Original array remains same arr1 : ", arr1);

Output

Using spread in function calls

The spread operator can be used to pass the elements of an array as individual arguments to a function.

function sum(a, b, c) {
  return a + b + c;
}

const values = [10, 20, 30];
const result = sum(...values);

console.log("Result = ", result); // Outputs: 60

Output

Math Object does not work on single array. With the help of spread operator, the array is broken into several individual elements.

let numbers = [11, 12, 800, -3, 0, -900, -100];
//console.log(Math.min(numbers)); //output NaN
console.log(Math.min(...numbers)); // Output -900

Spread operator with Objects

The spread operator can also be used to spread the properties of an object into another object. It’s useful for creating new objects based on existing ones.

const person = { name: "Rajalakshmi", age: 30 };
const updatedPerson = { ...person, age: 31, location: "Chennai" };

console.log(updatedPerson); // Outputs: { name: 'Rajalakshmi', age: 31, location: 'Chennai' }

Output

Concatenate or merge objects using spread parameter.

It is also possible to concatenate or merge objects using spread parameter.

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };

console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }

Output

Combining Rest with Spread

The spread operator can be combined with rest parameters to split and gather elements simultaneously.

function example(first, ...rest) {
  console.log("First Number: ", first); // First element
  console.log("Rest of the numbers", rest); // Array of remaining elements
}

const numbers1 = [1, 2, 3, 4, 5];
example(...numbers1); // Outputs: 1, [2, 3, 4, 5]

Output

Default Function Parameters

In JavaScript, default function parameters allow to specify default values for parameters directly in the function’s parameter list. This can make the code more concise and improve the readability of the functions.

Working of default parameters

Declaration with default values:

It is possible to declare default parameter values directly within the function’s parameter list using the assignment operator (`=`). When the function is called, if a value is not provided for that parameter or if `undefined` is passed, the default value will be used instead.

function sayHello(name = "Rajalakshmi", greeting = "Welcome") {
  console.log(`${greeting}, ${name}!`);
}

Declaration with default values – Usage

When a function with default parameters is called, it is possible to omit those parameters or explicitly pass `undefined` to indicate that the default value should be used.

function sayHello(name = "Rajalakshmi", greeting = "Welcome") {
  console.log(`${greeting}, ${name}!`);
}

sayHello(); //empty function call displays Welcome, Rajalakshmi!
sayHello("Priya"); //Single param displays Welcome, Priya!
sayHello("Sree", "Hi"); //Override and displays Hi, Sree!
sayHello("Kumar", ""); //Empty string displays , Kumar!

Output

Evaluation of Default values

Default parameter values are evaluated at the time the function is called, not when the function is defined. This means that any expressions used as default values are evaluated each time the function is invoked.

function increment(value, step = 1) {
  return value + step;
}

console.log(increment(5)); // Outputs: 6
console.log(increment(10, 2)); // Outputs: 12

Interaction with other Parameters

Default parameters can interact with other parameters in the function. Parameters with default values must come after parameters without default values in the parameter list.

function example(a, b = 5, c) {
  console.log(a, b, c);
}

example(1, undefined, 3); // Outputs: 1 5 3

Example

function example(value = null) {
  if (value === null) {
    console.log("Value not provided");
  } else {
    console.log("Value provided:", value);
  }
}
example();
example(7);
example(undefined);
example(false);
example(0);

Loading

Views: 10

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments