0

I worked with this piece of code today:

export class Triangle {
  constructor(...sides) {
    this.sides = sides;
    // returns e.g. [1,2,3] for Triangle(1,2,3)

    [this.a, this.b, this.c] = this.sides;

    // more code ...

The constructor was given with the spread operator as argument and I couldn't intuitively make sense of it, even tho I use deconstructuring and the spread operator regularly.

Loggin showed me that it results in an Array of whatever was inputed when the class was instantiated. Will that pattern always result in an Array, and if so why ?

Flip
  • 4,701
  • 5
  • 32
  • 63
  • 2
    That's not the spread syntax, that's the [rest parameter syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters): _"The rest parameter syntax allows a function to accept an indefinite number of arguments as an array"_ – Andreas Mar 25 '21 at 14:22
  • [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) -> _`...iter`  —  Three dots: spread syntax; rest parameters_ – Andreas Mar 25 '21 at 14:28
  • "*if so why ?*" the alternative is that it will sometimes result in an array. Inconsistency of your data type is *exceptionally* annoying. Pun intended. – VLAZ Mar 25 '21 at 14:35

2 Answers2

4

Yes, it will always result in an array. That syntax takes all of the arguments that were passed to the function, and gives them to you as an array. This is called "Rest parameters", and is useful when you want to make a variadic function. Ie, a function that can take an arbitrary number of arguments.

You also have the option to assign some of the arguments to individual variables, and then only gather up the remaining ones into an array:

constructor(first, second, ...rest) {

}

If the above is called with new Triangle (1, 2, 3, 4), then first will be 1, second will be 2, and rest will be the array [3, 4]

Nicholas Tower
  • 37,076
  • 4
  • 43
  • 60
2

Rest parameters

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

Syntax

function f(a, b, ...theArgs) {
  // ...
}

Description

A function definition's last parameter can be prefixed with "..." (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within a "standard" JavaScript array.. Only the last parameter in a function definition can be a rest parameter.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a)
  console.log("b", b)
  console.log("manyMoreArgs", manyMoreArgs)
}

myFun("one", "two", "three", "four", "five", "six")

// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

Copy&Paste from: Rest parameters - JavaScript | MDN

Andreas
  • 19,756
  • 7
  • 41
  • 49