The community is working on translating this tutorial into Croatian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
Function parameters with default values
In the previous article, we saw a lot of cool things we could do with function parameters. We also learned from the examples that JavaScript is quite flexible when it comes to function parameters - it doesn't care too much about whether you supply the expected arguments when calling a function or not. Instead, by default, any function parameter which isn't passed into the function by the caller will be "undefined".
However, sometimes it makes sense to provide a default value for a parameter instead of "undefined". Previous to the ES6 specification, JavaScript didn't allow you to do this directly, but it could be done with a workaround like this one:
function AddNumbers(n1, n2)
{
if(n1 === undefined)
n1 = 0;
if(n2 === undefined)
n2 = 0;
return n1 + n2;
}
alert(AddNumbers());
Notice how the function defines two parameters, but when I call it in the last line, I don't supply any arguments for it. However, in the function, I actually do a couple of checks for this, to make sure that we define a value for the parameters (n1 and n2) if no value is supplied by the function caller - the parameters now have a default/fallback value of 0.
One of the issues with this approach, besides the fact that it adds several lines of boring code to your function, is the fact that the caller of the function can't know that these parameters are actually not required, because they have a fallback/default value. Fortunately for us, default parameters was introduced in the ES6 specification, allowing you to define a default value for a function parameter.
Simple default values
The syntax for defining default values for a parameter is quite simple - you just assign a value to it directly in the function declaration. This value will act as a fallback value, instead of "undefined", in case the caller of the function doesn't supply it. Here's an example of it:
function AddNumbers(n1 = 0, n2 = 0, n3 = 0)
{
return n1 + n2 + n3;
}
alert(AddNumbers());
alert(AddNumbers(5, 10));
alert(AddNumbers(5, 5, 10));
I have now defined default values for all the parameters (0), and as you can see, I can then call the same function with zero or more arguments, without having to check the parameters for "undefined" in the function.
When calling a function with default parameter values, sometimes you will find yourself in a situation where you want to use the fallback value for the first parameter, but provide another value for one of the other parameters. The tricky part here is of course that if you want to supply a value for parameter #2, how do you let JavaScript know that you don't want to supply a value for parameter #1? Here's an example where we do just that:
function Greet(greeting = "Hello", target = "World")
{
alert(greeting + ", " + target + "!");
}
Greet();
Greet("Hi");
Greet(undefined, "Universe");
We call the Greet() function with various parameters, but notice the last line, where we call it with two arguments: The first argument is simply set to undefined, because when a function has a default value declared, JavaScript will always use this instead of undefined. This allows us to supply a real value for the second parameter, while still using the fallback value for the first parameter.
Complex default values
In some programming languages, default function parameter values are restricted to constant values, e.g. simple numbers and text strings. However, JavaScript is much more flexible in this regard. In fact, you can do pretty much anything - JavaScript will simply evaluate the statement you supply as any other kind of JavaScript code, when calling the function. Let's look at some of the things this will allow you to do.
Math and referencing other parameters
Please notice: This example is completely useless on its own but simply shows you that you can do math, even referencing other parameters, when defining default values for parameters:
function AddNumbers(n1 = 0, n2 = 2 + 2, n3 = n2 - 8)
{
return n1 + n2 + n3;
}
alert(AddNumbers());
Instantiating objects
You can instantiate new objects and use them as default values, e.g. a Date object, like this:
function Greet(greeting = "Hello", target = "World", date = new Date())
{
alert("A greeting from " + date.toString() + ": " + greeting + ", " + target + "!");
}
Greet();
Calling functions
Just as well as you can instantiate an object, you can of course call a simple function and use the returned value as the default value for the parameter:
function AddNumbers(n1 = 0, n2 = Math.random() * 10)
{
return n1 + n2;
}
alert(AddNumbers());
In this example, I call the Math.random() function to get a random number between 0 and 1, then multiply it by 10, for the second parameter.
Required parameters using default values
You are of course free to call your own functions as well, and in fact, this allows us to do something pretty cool. We previously talked about the fact that JavaScript doesn't enforce parameters when calling a function - if a function declares one or several parameters, you are free to call this function without specifying any parameters.
In this situation, the function will have to handle the fact that it can't rely on the parameters having any value, usually by supplying a default value or by checking, before using the parameter, if it has the expected value. However, sometimes this is not optimal and you would wish that JavaScript would just force the caller of the function to supply the expected amount of variables, and hallelujah, we can actually accomplish just that, using default values:
function Required()
{
// Leave out the alert if using this code
alert("Please specify a value for this function parameter!");
throw new Error("Please specify a value for this function parameter!");
}
function AddNumbers(n1 = Required(), n2 = Required())
{
return n1 + n2;
}
alert(AddNumbers());
alert(AddNumbers(5, 10));
First things first: You should probably not include the alert() part if using this code - it's only included to show you that something is happening if you run this example. In a real world scenario, you probably don't want to bother the user of your website with an implementation detail like this.
So, what I'm doing here is I have defined a function called Required(). I set this as the default value for the two parameters of the AddNumbers() function, which means that whenever AddNumbers() is called with insufficient arguments, the Required() function is called automatically. In the Required() function, we throw an Error, which will halt the execution of the code.
By doing so, we have made sure that nothing will really work if the parameters are not provided by the caller of the function and thereby making the parameters required. In other words, we have just added a feature to the JavaScript language which didn't exist before, thanks to the extreme flexibility of the language in general and the default function values in particular. Pretty cool, right?
Summary
With default parameter values, you can supply your functions with fallback values, which will be used if the caller of the function fails to supply them. The default parameter values can be simple types like numbers or strings, or even more complex operations like invoking a function.