Javascript

Rest parameter syntax & Spread Operator in JavaScript

In this article, we are going to explore the triple dots (...) syntax that JavaScript provides. Its mechanisms, and why they are...

Written by Luci · 1 min read >

In this article, we are going to explore the triple dots (...) syntax that JavaScript provides. Its mechanisms, and why they are not operators.

Essentially, the triple dot syntax is used for a couple of mechanisms:

  • Rest syntax for receiving data.
  • Spreading for sending data.

Receiving data: rest parameter syntax

A rest parameter is a peculiar kind of parameter that receives all remaining arguments of a function call via an Array:

function foo(first, ...rest) { 
function foo(first, ...rest) { 
  return { first, rest } 
}
foo('a', 'b', 'c');
// { first: 'a', rest: [ 'b', 'c' ] }

We can also use the rest syntax in Array-destructuring:

const [head, ...tail] = ['a', 'b', 'c'];
head
//'a'
tail
// [ 'b', 'c' ]

And we can use it in object-destructuring:

const { first: f, ...rest} = {
  first: 'Petter', 
  last: 'Parker', 
  age: 19
};
f
// 'Petter'
rest
// { last: 'Parker', age: 19 }

Sending data: spread operator

Using the spread operator in a function call turns Array elements into function call arguments.

function returnArgArray(...args) { 
  return args;
}
returnArgArray(...['x', 'y', 'z']);
//[ 'x', 'y', 'z' ]

We can also spread Arrays into Array literals:

[...['a', 'b'], 'c']
// [ 'a', 'b', 'c' ]

And we can spread objects into object literals:

{...{ a:1, b:2 }, c:3}
// { a: 1, b: 2, c: 3 }

Rest and spread are not operators

Operators such as + or await are used to write independent expressions that evaluate values. We can use those expressions in many contexts.

In contrast, rest and spread are part of their surroundings. That’s why they shouldn’t be called operators:

  • Rest syntax: rest parameters (function definitions), rest elements (Array-destructuring), rest properties (object-destructuring)
  • With spreading, I usually say: “spreading into …” (function calls, Array literals, object literals).

Further reading (use cases, etc.)

Rest syntax:

Spreading:

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x