Now that we have a better understanding of JavaScript Functions, we can now provide optional arguments to those functions. Why would you want an optional argument in a function you might ask? Well, there are many different reasons, but a good example is in the actual structure of JavaScript. For example, the string method of split has a required argument and an optional one. The required argument is the separator, which is what character(s) you will use to divide the string. The optional argument is limit where you specify how many times you want to split the string. So, if I only wanted to split the string to the first instance of the separator, I would just provide a 1. Example please!
How Optional Arguments Work
Now, we put in the optional argument of 1.
That is cool and all, but how exactly do we create functions that can do this? If we create a function with 2 arguments and only provide 1, the second argument will return undefined. First, JavaScript doesn’t yell at you if you have multiple arguments, but don’t specify them when you call the function. JavaScript only screams bloody murder when you leave off an argument that sets a variable inside the function that is called. For example…
See JavaScript doesn’t care that you left off the message argument because it didn’t need it anywhere in the function. Now, if you were to use message in the function, it would return undefined.
Creating Optional Arguments
Let’s get back to actually creating optional arguments in our functions. You will notice that the easiest and best way to create optional arguments is to put them at the end of the argument list. Sometimes you might want two optional arguments where only one has to be required. However, that is much more complicated and outside the scope of this simple tutorial.
See how simple it really is? All we did was create an if statement to check if the function call specified an argument message by seeing if it was equal to undefined. Since it was undefined, we went ahead and assigned our own value to the message variable. So when JavaScript finally saw us using the message variable, it didn’t think twice of wondering why it wasn’t specified in the function call.
References
This page should explain what "console.log" does.