'Javascript Property with three dots (...)

I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:

export const Something = class Something {
    constructor(someObject = {}) {
        this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
    };
// The rest of the class
};

I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?



Solution 1:[1]

... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.

I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator). The following has been explained with examples in this stackoverflow answer.

  1. Combine Arrays (Concatenate Arrays)
  2. Copying Arrays
  3. Calling Functions without Apply
  4. Destructuring Arrays
  5. Function Arguments as Rest Parameters
  6. Using Math Functions
  7. Combining Two Objects
  8. Separate a String into Separate Characters

Solution 2:[2]

The [...something] is the spread operator. It in essence allows for an array or string to be expanded. You will see it used often in React, but has many other use cases.

MDN has great documentation on the spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Solution 3:[3]

You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':

const data= { name: "John", age: 24 };

const newData = {
  ...data, // Here
  sex: "Male"
}

console.log(newData);

This is the result:

{ name: "John", age: 24, sex: "Male" }

This is other example with "...data[key]" to add "id" to each object in an array:

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key),
    ...data[key] // Here
  }

  newData.push(obj);
}

console.log(newData);

This is the result:

[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Keet Sugathadasa
Solution 2 bdurb
Solution 3 Kai - Kazuya Ito