ES6 introduces rest parameters. Rest parameters allow us to send an arbitrary number of parameters to a function in the form of an array. Rest parameter can only be the last one in the list of parameters, and there can only be one rest parameter. Putting a rest operator(...
) before the last formal parameter indicates that parameter is a rest parameter. The following example shows adding a rest operator before the last formal parameter:
function sayThings(tone, ...quotes){ console.log(Array.isArray(quotes)); //true console.log(`In ${tone} voice, I say ${quotes}`) } sayThings("Morgan Freeman","Something serious"," Imploding Universe"," Amen"); //In Morgan Freeman voice, I say Something serious, Imploding Universe,Amen
The first parameter passed to the function is received in tone
, while the rest of the parameters are received as an array. Variable arguments (var-args) have been part of several other languages and a welcome edition to ES6. Rest parameters can replace the slightly controversial arguments
variable. The major difference between rest parameters and the arguments
variable is that the rest parameters are real arrays. All array methods are available to rest parameters.
3.144.244.250