7

I learned about this thing from this post.

function StoreMixin(...stores) { // what is "..."
  var Mixin = {
    getInitialState() {
      return this.getStateFromStores(this.props);
    },
    componentDidMount() {
      stores.forEach(store =>
        store.addChangeListener(this.handleStoresChanged)
      );
      this.setState(this.getStateFromStores(this.props));
    },
    componentWillUnmount() {
      stores.forEach(store =>
        store.removeChangeListener(this.handleStoresChanged)
      );
    },
    handleStoresChanged() {
      if (this.isMounted()) {
        this.setState(this.getStateFromStores(this.props));
      }
    }
  };
  return Mixin;
}

Please kindly explain what is "...", with example code. Thanks!

Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129
  • Does this answer your question? [Spread Syntax vs Rest Parameter in ES2015 / ES6](https://stackoverflow.com/questions/33898512/spread-syntax-vs-rest-parameter-in-es2015-es6) – Henke Mar 16 '21 at 07:59

1 Answers1

16

In that example, the ... is a Rest parameter, a syntax allows us to represent an indefinite number of arguments as an array.

It is somewhat similar (or not :), but it's not the same as the spread syntax.

In your example, the stores argument inside is an array. If function StoreMixin(...stores) is called like StoreMixin(1,2,3) then stores will be [1, 2, 3] and so on.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • Thanks, this is the part that confuses me. Since the syntax is the same, how does Javascript knows if I want to put all params in an array(Rest parameter), or destruct an object into variables(spread syntax)? If they both are used in function params. – Nicolas S.Xu Apr 21 '18 at 16:01
  • @NicolasS.Xu - Destructuring of function arguments is simply not the same syntax. Easy for the interpreter to tell the difference. – jfriend00 Apr 21 '18 at 16:09
  • 1
    Actually, only rest parameters can be used in functions arguments **declarations**. You can't use spread there. Spread is used everywhere *else*, though. – acdcjunior Apr 21 '18 at 16:09
  • @acdcjunior I see. "..." is the same, but it is "rest" operator in function definition, "spread" is used in function invocation. gosh... Thanks a lot! – Nicolas S.Xu Apr 21 '18 at 16:17
  • 1
    It is best not to think of it as an operator. It is part of the function declaration syntax overall, and in that context it can mean only one thing. Spread is part of call and array syntax, and in that context the ellipsis can only be spread. – loganfsmyth Apr 21 '18 at 16:54
  • @NicolasS.Xu: Consider `()`. It's used for three different things: Function definition, function call and as grouping operator. The context makes it clear what the meaning of `()` is. – Felix Kling Apr 21 '18 at 23:37