DEV Community

Discussion on: 5 Uses for the Spread Operator

Collapse
 
jacobmgevans profile image
Jacob Evans

I would love some real-world use cases for Rest as well. I rarely use it but I feel like thats because I lack enough understanding. Same goes with Switch though, I need to just use them more lol

Collapse
 
laurieontech profile image
Laurie

Noted! Maybe I'll get to those in the future.

Collapse
 
jacobmgevans profile image
Jacob Evans

Awesome! Thank you for listening to my suggestion!

Collapse
 
kenbellows profile image
Ken Bellows

I find rest parameters super useful for writing wrapper functions. For a super simple example, I often like to define small logger functions as wrappers around console.log() that always add certain context, such as a label that tells me where the log was issued:

const log = (...args) => console.log('MyFile.js ::', ...args)

// ... later
const payload = {
  name: 'Ken',
  job: 'Web dev'
}
log('Sending:', payload)
// => MyFile.js :: Sending: { "name": "Ken", "job": "Web dev" }

This is a pretty trivial example, but I've used it for much more complicated cases where I basically always use the same default arguments for calls to library functions with lots of arguments, and I want a wrapper that supplies all but the last couple arguments for me. I'll write a wrapper that gathers arguments into a rest array, then spreads them into the end of my call to the library function, like I did with console.log above

Collapse
 
jacobmgevans profile image
Jacob Evans

This is super awesome. I can see the value already! Thank you so much! 😁