spread and rest operators

Usually, when we execute such functions, we have to put in the parameters one by one…

or

In es5, we would use the apply function to do this:

By definition, function prototype apply takes in all the parameters as an array. Hence we make use of the apply function to pass in parameters using an array.

However in es6, you can simply use the spread operator:

Rest Parameters

Every function has an object called arguments.
It is an array-like object that keeps track of all dynamic number of parameters throw into the function.

An array-like object simply means that the object holds:

1) numerical property either in string or integer
2) has length property

You can convert Array-like Objects to their Array counterparts using Array.prototype.slice

This is so that we can convert arguments object into an array.

1) We know that slice creates a new array, with shallow data.
2) We also know that there is a Function prototype called call.

functionName.call(value of this, arg1, arg2…)When using call, we go someFunctiono.call(PersonObj), and it would execute function DisplayInfo using PersonObj as ‘this’

We want to execute function Array.prototype.slice usinga function’s arguments object as ‘this’:
– Array.prototype.slice.call(arguments)


tmp5
Array(10) [ undefined, "hohoho merry xmas", "happy new year", undefined, undefined, undefined, undefined, undefined, undefined, "testing 1 2 3" ]

arguments.slice() does not work.

arguments is an array-like object. And js objects do not have the prototype function slice().

Thus, in our example, we simply use Array.prototype.slice.call to create a new array shallowly from the arguments object.
Once we get that array, we simply iterate through it and do what we like.

call isFullAge5 with various parameters


[ 1980, 1990, 2000, 2019 ]
true
true
true
false

es6

Using spread operator is same as let arr = Array.prototype.call(arguments) where arguments is an object.

Even better is if we put variables in front. Doing so put the first parameter into ‘limit’. And then mask the
rest of the parameters into array years.