0

I recently learned about this awesome method of declaring a function's variables using an object with preset defaults. Does this method have a name?

function test({var1= 'hello', var2= 'world'} = {}) { console.log(var1, var2); }
test(); // result 'hello world'
test({var2: 'universe'}) // result 'hello universe'

I am also not sure why it requires the object to be "= {}"

For the Name
  • 2,032
  • 12
  • 16
  • 2
    This is called as [Object Destructuing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) See the section **Setting a function parameter's default value** for this particular case – Maheer Ali Nov 15 '19 at 18:59
  • 3
    ^ Specifically these 2 sections: [Unpacking fields from objects passed as function parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter) and [Setting a function parameter's default value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Setting_a_function_parameters_default_value) – adiga Nov 15 '19 at 19:02

0 Answers0