added destructuring for rest parameters and formal parameters (#20759)
This commit is contained in:
committed by
Martin Payne
parent
0ec3c322a4
commit
1023a46311
@ -97,5 +97,27 @@ The rest parameter must always come as the last argument in your function defini
|
|||||||
//function body
|
//function body
|
||||||
}```
|
}```
|
||||||
|
|
||||||
|
so doing this should throw a SyntaxError: Rest parameter must be last formal parameter
|
||||||
|
```function invalidRestUse(...args, arg1, arg2){
|
||||||
|
}```
|
||||||
|
|
||||||
|
Rest parameters can be destuctured and unpacked into distinct variables
|
||||||
|
```
|
||||||
|
function restDestructuring(...[a, b, c]){
|
||||||
|
return a + b + c;
|
||||||
|
}
|
||||||
|
|
||||||
|
restDestructuring(1, 2, 3); // 6
|
||||||
|
```
|
||||||
|
### ES6 destructuring of arrays in formal parameter
|
||||||
|
|
||||||
|
With the new destructuring feature we can even go one step ahead when passing an array to a function and break down its elements as variables.
|
||||||
|
```
|
||||||
|
function arrayDestructuring([a, b, c]){
|
||||||
|
return a + b + c;
|
||||||
|
}
|
||||||
|
|
||||||
|
arrayDestructuring([1,2]) //Nan , as 1 + 2 + undefined = NaN
|
||||||
|
arrayDestructuring([1,2,3]) // 6
|
||||||
|
arrayDestructuring([1,2,3,4,5]) // 6 additional elements will be ignored
|
||||||
|
```
|
||||||
|
Reference in New Issue
Block a user