DEV Community

Discussion on: JavaScript Best Practices — Rest Operator

Collapse
 
wulymammoth profile image
David • Edited

Nice post, John, but sorry for being a bit pedantic -- this is syntax and the idea is best known as "rest parameters" (not to be confused with REST) according to MDN.

One example that often isn't shown that I'd like to share is in the use of recursive operations:

function headOperation(arr, operation) {
  if (arr.length === 0) return; // base case (empty array) - terminate
  const [head, ...tail] = arr;
  operation(head);
  headOperation(tail); // operate on rest of list (tail)
}
Collapse
 
aumayeung profile image
John Au-Yeung

I think it's a great use of the rest syntax.

Anything is better than using arguments to get the arguments.

Collapse
 
wulymammoth profile image
David

Not necessary in JS, but this is very common in functional programming languages where loops constructs don't exist but all recursive calls are TCO (tail-call optimized)