JavaScript Rest Parameters and Spread Syntax

JavaScript Rest Parameters and Spread Syntax

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this article, we will see what the rest parameters and what spread syntax is all about.

The example below is a summary of this article.

const peopleGrades = (index, ...numbers) => {  /* ...rest */
  const array = [ ...numbers ]; // ...spread
  return array[index]; // 8 => [ 4, 5, 2, 8, 2 ][3]
};

peopleGrades(3, 4, 5, 2, 8, 2); // 8

Rest Parameter

A function will only perform operations on parameters and variables in the function body.

See the example below:

const sum = (a, b) => {
  return a + b; // 2 + 3
}

console.log( sum(2, 3, 1, 10, 4) ); // 5

Notice the operation in the function body is based on the number of parameters, not the number of arguments in the calling function.

We can re-consider passing all arguments including 1, 10, 4 to the parameter for a returned computation in the function body.

See the example below:

const sum = (a, b, c, d, e) => {
  return a + b + c + d + e; // 2 + 3 + 1 + 10 + 4
};

console.log( sum(2, 3, 1, 10, 4) ); // 20

Passing arguments to the parameters shown above is not advisable. In JavaScript, it is advisable to use the Rest parameter to represent more than three parameters.

A rest parameter looks like ...args. The three dots ... represents more parameters.

See the syntax below:

func = (...args) => {
  ...
};

func(args);

Where args = array of parameters name.

The example below proves that the args is a list of arguments.

const sumFunc = (...args) => {
  return args; 
};

// let's gather all arguments into the array 
console.log( sumFunc(2, 3, 1, 10, 4) ); // [ 2, 3, 1, 10, 4 ]

Since args is an array of arguments, we can sum each argument in the array.

See the example below:

const sumFunc = (...args) => {
  const sum = args[0] + args[1] + args[2] + args[3] + args[4];
  return sum; // 2 + 3 + 1 + 10 + 4
};

// let's sum all arguments in the array 
console.log( sumFunc(2, 3, 1, 10, 4) ); // 20

See another example below:

const sumFunc = (sum = 0, ...args) => {

  for (let arg of args) {
    sum = sum + arg ;
  }

  return sum;
};

console.log( sumFunc(2, 3, 1, 10, 4) ); // 20

Let's see another example below:

const employee = (name, ...titles) => {
  const personTitles = `${name} is a ${titles[0]}, 
  ${titles[1]}, ${titles[2]}, and ${titles[3]}`;
  return personTitles;
};

// let's gather all arguments into array 
console.log(
  employee('John', 'web developer', 'doctor',
    'consultant', 'professor')
);

The ...args must always be the last parameter.

The example below will be invalid.

const employee= (...titles, name) => {
  const personTitles = `${name} is a ${titles[0]}, 
  ${titles[1]}, ${titles[2]}, and ${titles[3]}`;
  return personTitles;
};

console.log( 
  employee('web developer', 'doctor', 
  'consultant', 'professor', 'John')
  ); // SyntaxError: Rest parameter must be last formal parameter

Spread Syntax

The spread works on iterable like strings, arrays, objects, etc.

The spread syntax is quite different from the rest syntax.

See the example below:

const staff = (str) => {
  const employee = [ ...str ];
  return employee;
};

console.log( staff('Bello') ); // [ 'B', 'e', 'l', 'l', 'o' ]

See another example below:

const staff = (recruiter) => {
  const batch1Recruits = [ 'John', 'Sarah', 'Angelina', 'Tom' ];
  const batch2Recruits = [ 'Bob', 'Jack', 'Lucky', 'Ali' ];
  const newEmployees = [ recruiter, ...batch1Recruits, ...batch2Recruits ];
  return newEmployees;
};

console.log( staff('Patricia') );
/*
[
  'Patricia', 'John',
  'Sarah',    'Angelina',
  'Tom',      'Bob',
  'Jack',     'Lucky',
  'Ali'
]
*/

The spread syntax works for iterable - string, arrays, objects, maps, sets, etc

Let see one last example, but on an object:

const myDetails = { age: 27, isDoctor: false };

const dataBase = { name: 'Bello', ...myDetails };

console.log(dataBase);
// { name: 'Bello', age: 27, isDoctor: false }

Happy coding!!!


Buy me a Coffee


 
Share this

Impressum

TechStack Media was launched in the year 2020 to make the learning of web technologies easier and more fun.

My name is Bello Osagie, I am the founder of TechStack, and my focus is to give in-depth, senior-level knowledge of the course through a step-by-step approach. You will learn HTML, CSS, JavaScript etc.

You can find my posts on Dev.to, Medium, Hashnode, Hackernoon, and Blogspot

The approach is to first start with the basics, then advance to more topics. Lots of practical examples are added to make learning more easier. TechStack Media also includes videos apart from content writing to make sure you understand all the concepts in a particular topic or course. Contents are frequently updated, so you do not miss out on the latest technology.

If you need a contact me on any of my social media or email:

For exclusive web technology tutorials, join my patron page.

Proudly part of