Optional arguments

Setting optional arguments for functions is thankfully a pretty simple endeavor! If you want to make a function argument optional, all you need to do is add an equals sign after the name of the parameter and give it a default value. For example, let's revisit the sayHello function we wrote a little bit earlier in this chapter:

const sayHello = name => {
console.log(`Hello ${name}!`);
};

Now, let's modify that so that if someone doesn't specify a name, the function call will not just fail out or throw an error for the developer:

const sayHello = (name = "Unknown") => {
console.log(`Hello ${name}!`);
};

Note that since we're using an optional variable for the argument list, we need to enclose it in parentheses again! Now, if someone were to call that function without specifying any parameters, we'd expect to see in our console Hello Unknown!, something similar to the following:

sayHello();

With that, let's write this into our previous headerDisplay function. It will be a little messy, sure, but it's great to know how to use this effectively, since it's a great way to implement defensive programming in your projects:

const headerDisplay = ({
header: title = "Todo List",
headerColor: color = "blue"
}) => <h2 style={{ color: color }}>{title}</h2>;

Now, if we were to go back and change our App component's call to the header() function to just pass in a blank object, we would expect the header to instead say TodoList with a blue header:

const App = () => (
<div className="App">
{headerDisplay({})}
<br />
<TodoList />
</div>
);

Let's see the results before we revert the change to our header function and change it back into passing in the details variable:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172