Flip
Flip

Reputation: 6761

Will the spread operator as argument of a (constructor) function always result in an Array, and if so, why?

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 ?

Upvotes: 0

Views: 1122

Answers (2)

Andreas
Andreas

Reputation: 21911

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

Upvotes: 2

Nicholas Tower
Nicholas Tower

Reputation: 85062

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]

Upvotes: 4

Related Questions