Passing default values to an object parameter

Passing default values to an object parameter

Passing default values to function parameters can avoid nasty 'undefined' surprises and give us better control over our code. Open parenthesis, write a variable name, add equals, write the initial value you want, and close parenthesis. Easy peasy. Now, how to do the same when the parameter is an object?

Not a big deal, but it can be tricky.

The first example below seems to be the most intuitive one. However, note that it will throw an error because the function is expecting an object as the argument. The default values only work if the function is invoked like so: sendNewCoffee({}).

The second example solves that issue. When declaring the parameter we have to equal the object to an empty object. That way we are basically giving the object its own default value.

default_00.jpg