WTF do these three dots in React do?

Post Image for WTF do these three dots in React do?

Yes. You see this a lot in React ..., but in fact, this is not React code but JavaScript.

The rest and spread operators are two different names for the same three ... dots.

In one case, you can combine elements together with, and in the other, you can ...spread out an array into arguments (or even spread an object into another object).

When used in function arguments of a function declaration/expression, it will convert the remaining arguments into an array. This variant is called the Rest parameter syntax.

function sum(x, y, z) {
  return x + y + z

const numbers = [1, 2, 3]

// expected output: 6

console.log(sum.apply(null, numbers))
// expected output: 6

In other cases, it will spread out the values of an iterable in places where zero or more arguments or elements are expected. This variant is called the Spread syntax.

function fn(x, y, z) {}
const args = [0, 1, 2]
fn.apply(null, args)

With spread syntax the above can be written as:

function fn(x, y, z) {}
const args = [0, 1, 2]

There’s an easy way to distinguish between them:

When ... is at the end of function parameters, it’s rest parameters and gathers the rest of the list of arguments into an array.

When ... occurs in a function call or alike, it’s called a spread syntax and expands an array into a list.

© Lauro Silva, LLC. All rights reserved.