Using the JavaScript object rest operator in function parameters
🛌

Using the JavaScript object rest operator in function parameters

Tags
JavaScript
Created
Jul 23, 2021 11:51 PM
When you use the object rest operator in a function's parameters, the rest parameter becomes an object that holds all the properties not explicitly specified in the parameter:
function choose({ choice, ...availableChoices }) {
  if (availableChoices[choice]) {
    availableChoices[choice]()
  } else {
    console.log(`${choice} not available`)
  }
}

choose({
  choice: process.argv[2],
  fries: () => console.log('you chose fries'),
  chips: () => console.log('you chose chips'),
  salad: () => console.log('you chose salad'),
  fruit: () => console.log('you chose fruit'),
})
 
This is very similar to using the rest operator during object destructuring, for example:
const { choice, ...availableChoices } = {
  choice: process.argv[2],
  fries: () => console.log('you chose fries'),
  chips: () => console.log('you chose chips'),
  salad: () => console.log('you chose salad'),
  fruit: () => console.log('you chose fruit'),
}

if (availableChoices[choice]) {
  availableChoices[choice]()
} else {
  console.log(`${choice} not available`)
}
 
This is also very similar to using **kwargs (keyword arguments) in Python:
import sys

def choose(choice, **available_choices):
  if choice in available_choices:
    available_choices[choice]()
  else:
    print(f'{choice} not available')

if __name__ == "__main__":
  choose(
    choice = sys.argv[1],
    fries = lambda: print('you chose fries'),
    chips = lambda: print('you chose chips'),
    salad = lambda: print('you chose salad'),
    fruit = lambda: print('you chose fruit'),
  )