官术网_书友最值得收藏!

JavaScript rest and spread syntax

In JavaScript, a rest parameter collects multiple arguments and condenses them into a single argument. It is called rest because it collects the rest of the arguments into a single argument.

A rest parameter has nothing to do with Representational state transfer protocol (REST ).

This syntax was introduced in ES6 and allows us to nicely implement functions that have an indefinite number of parameters.

We define a rest parameter with three dots preceding the parameter name.

Let's go through a quick example:

  1. Let's create a logScores function that takes in a scores rest parameter that just outputs the parameter to the console:
function logScores(...scores) {
console.log(scores);
}
This is pure JavaScript - we'll introduce types to rest parameters when we look at the new features in TypeScript 3.
  1. We can call logScores as follows:
logScores(50, 85, 75);

If we run this, we'll get an array of the three elements we passed in as parameters output to the console. So, our scores parameter has collected all the arguments into an array.

The spread syntax is the opposite of rest parameters. It allows an iterable, such as array, to be expanded into function arguments.

Let's look at an example:

  1. Let's redefine our logScore function with specific parameters:
function logScore(score1, score2, score3) {
console.log(score1, score2, score3);
}

  Note that this is still pure JavaScript – no types just yet! 

  1. Let's define a scores array:
const scores = [75, 65, 80];
  1. Finally, let's use the spread syntax to pass our scores variable into our logScore function:
logScore(...scores);

If you are using the TypeScript playground, you'll get the compilation error, expected 3 arguments, but got 0 or moreThe program still runs though, because this is perfectly valid JavaScript. 75, 65, 80 will be output to the console if we do run it.

In the following sections, we'll see how the new features in TypeScript 3 help us help the compiler to better understand what we are trying to do when using rest and spread. This will allow us to resolve the compilation errors seen in the preceding example.

主站蜘蛛池模板: 贞丰县| 南阳市| 涟水县| 垣曲县| 永康市| 新乡市| 龙口市| 铁岭市| 保德县| 萨迦县| 班戈县| 忻城县| 玉山县| 辽源市| 四川省| 阳信县| 平泉县| 柞水县| 浑源县| 虹口区| 古丈县| 贵德县| 南宫市| 静安区| 咸宁市| 无棣县| 梁河县| 阿鲁科尔沁旗| 兴城市| 莎车县| 辰溪县| 突泉县| 房产| 得荣县| 丽水市| 沧州市| 调兵山市| 精河县| 九江县| 大竹县| 林口县|