Lesson 15. Default parameters and rest

 

After reading lesson 15, you will

  • Know how to use default parameters
  • Know how to gather parameters with the rest operator
  • Know how to use rest to pass arguments between functions

Sometimes new language features provide ways to achieve things that were impossible or nearly impossible to do before. Other times they simply add a nicer way of achieving something that was already easily implemented. But just because something is easy to implement or requires few lines of code to do, doesn’t necessarily make it readable. That’s exactly what default function parameters and rest parameters do: they provide a more concise and much more readable way of achieving something.

Consider this

By looking at this implementation of the pluck function, can you quickly tell what it’s doing? That first line—what is it doing? That line requires too much thought. In its current state it probably needs a comment explaining what it does.

function pluck(object) {
  const props = Array.from(arguments).slice(1);
  return props.map(function(property) {
    return object[property];
  });
}
const [ name, desc, price ] =
pluck(product, 'name', 'description', 'price');

15.1. Default parameters

15.2. Using default params to skip recalculating values

15.3. Gathering parameters with the rest operator

15.4. Using rest to pass arguments between functions

Summary