cft

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.


user

Daniel Martorell

2 years ago | 1 min read

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.

Example of good and not so good practice.

Upvote


user
Created by

Daniel Martorell

Javascript Developer || React JS & CSS enthusiast


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles