Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "foo(...arg)" (three dots in a function call)?

Tags:

javascript

Can someone tell what is "..." in the below code in the "Intro to Angular" example?

getHeroes() {
    this.backend.getAll(Hero).then( (heroes: Hero[]) => {
      this.logger.log(`Fetched ${heroes.length} heroes.`);
      this.heroes.push(...heroes); // fill cache
    });
like image 208
vineel Avatar asked Feb 08 '17 16:02

vineel


People also ask

What is the meaning of ARGs?

Alternate reality games (ARGs), also sometimes called pervasive games or transmedia storytelling, are designed to combine real life and digital game play elements. So that you are playing the game in the real world but doing behaviors that are linked to the game. (my addition.)

How does ARGs work in JavaScript?

args is a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters.

What is the rest operator in JavaScript?

What Exactly Is the Rest Operator? The rest operator is used to put the rest of some specific user-supplied values into a JavaScript array. The three dots ( ... ) in the snippet above symbolize the rest operator. The text after the rest operator references the values you wish to encase inside an array.


1 Answers

This has nothing to do with jQuery or Angular. It's a feature that was introduced in ES2015.

This particular use of ... doesn't actually have an official name. A name that is in line with other uses would be "spread argument" (a generic term would be "spread syntax"). It "explodes" (spreads) an iterable and passes each value as argument to the function. Your example is equivalent to:

this.heroes.push.apply(this.heroes, Array.from(heroes));

Besides being more concise, another advantage of ... here is that it can be more easily used with other concrete arguments:

func(first, second, ...theRest);

// as opposed to the following or something similar:
 func.apply(null, [first, second].concat(Array.from(heroes)));
like image 151
Felix Kling Avatar answered Oct 24 '22 17:10

Felix Kling