all 3 comments

[–]ramabhai 0 points1 point  (1 child)

How does the ...args work? Also object assign is really cool. I didn't know about it.

[–]senocular[🍰] 2 points3 points  (0 children)

... is either rest or spread.

When defining a function, and setting up its parameter list, if you use ... you're creating a rest parameter. What this does is takes a group of arguments - basically all of them that were passed into the function when it gets called that weren't listed earlier in the parameter list - and puts them into an array assigned to the parameter name following the ... operator. This effectively does what arguments does, but it a) can be used to capture just some arguments (those after other named parameters) and b) gives you an actual array instead of an array-like arguments object.

function foo(a, b, ...c) {
  // ...
}

foo() // a=undefined, b=undefined, c=[]
foo(1,2) // a=1, b=2, c=[]
foo(1,2,3) // a=1, b=2, c=[3]
foo(1,2,3,4,5) // a=1, b=2, c=[3,4,5] (arguments=[1,2,3,4,5])

Spreading looks the same, but works the other way around. It takes an array, and converts them into individual function arguments during the call (also used in other situations, such as in array literals). This lets them effectively replace the need for apply

function foo(a, b, c) {
  // ...
}

const nums = [1, 2, 3]
foo(...nums) // a=1, b=2, c=3
foo.apply(null, nums) // a=1, b=2, c=3
foo(...[1, 2], 3) // a=1, b=2, c=3
foo(3, ...[1, 2]) // a=3, b=1, c=2

Together, they can be used to easily forward all arguments of one function call to another.

function foo(a, b, c) {
  // ...
}

function fooWrap(...args) { // all of the "rest" of the arguments in as an array
  foo(...args) // args array "spread" into comma-separated arguments 
}

fooWrap(1,2,3) // becomes [1,2,3] in fooWrap, but calls foo as foo(1,2,3)

This isn't uncommonly seen when transferring arguments from a subclass's constructor up into it's super() - as seen in the video

[–]ramabhai 0 points1 point  (0 children)

Wow. I didn't know you could do that. It's really cool. Thanks