I am confused about the spread syntax and rest parameter in ES2015. Can anybody explain the difference between them with proper examples?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
ES6 has new feature three dots
...
Here is how we can use these dots:
Here
...m
is a collector, it collects the rest of the parameters. Internally when we write:var [c, ...m] = [1,2,3,4,5];
JavaScript does followingHere,
...params
spreads so as to adding all of its elements toother
Internally JavaScript does following
Hope this helps.
Added in ES6 these three dots
...
has two meanings, Spread operator and Rest parameterSpread operator: You use the three dots to expand
iterables
, byiterables
I meanarrays
,string
, etc. As arguments. For exampleMath.max()
function expect an indeterminate number of arguments so you can use Spread operator to expand elements as arguments onMath.max()
function. Here an example from mdnAnother use case is to add, for example having this array
You can add it to another array
Then
favoritesVideoGames
value isAbout Rest parameter, here the MDN definition
This means you can pack many elements into a single element
Here an example from MDN
I usually get confused with these three points, this illustration by @stephaniecodes helps me to remember its logic. I mention that I took inspiration from this illustration to answer this question.
I hope it is useful.
considering 3 scenarios
1] without using any operator
2] with rest operator
- we can gather any number of arguments into an array
3] with spread operator
another one
Summary:
In javascript the
...
is overloaded. It performs a different operations based on where the operator is used:Example:
Rest parameter syntax:
Spread syntax:
Basically like in Python:
In reference to this i cant understand how we are passing a function and returning arguments in javascript
Function is a set of instructions that takes some input and processes them and returns result.
here we have an array [1, 2, 3, 4, 5, 6], and filter function iterates over each element and passes each element to positive functions which returns the number if it is even, else skips it.
trace:
hence the result [2, 4, 6]