I am writing a Javascript function with an optional argument, and I want to assign the optional argument a default value. How can I assign it a default value?
I thought it would be this, but it doesn't work:
function(nodeBox,str = "hai")
{
// ...
}
To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==
Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
ES6 Update - ES6 (ES2015 specification) allows for default parameters
The following will work just fine in an ES6 (ES015) environment...
function(nodeBox, str="hai")
{
// ...
}
You can also do this with ArgueJS:
function (){
arguments = __({nodebox: undefined, str: [String: "hai"]})
// and now on, you can access your arguments by
// arguments.nodebox and arguments.str
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With