In JavaScript, you can declare functions and give them parameters, like so:
function myFunction(param1, param2) {
// The code for your function goes here
}
If you don’t assign a value to a parameter when you call a function, that parameter’s value will default to undefined
. And if you don’t handle this within the logic of your function, it’ll break.
You can prevent your function from breaking by assigning a default value to that parameter, effectively making that parameter optional (in other words, in the case that the function’s call doesn’t define a value for it, it will default to the default value provided by you).
Making a Parameter Optional by Assigning It a Default Value
To declare a JavaScript function with an optional parameter, assign a default value to that parameter. If a value isn’t provided for the optional parameter when the function is called, the default value will be used instead.
Here’s an example:
// Declare function
function myFunction(param1, param2 = 'world') {
console.log(param1 + ', ' + param2 + '!')
}
// Call function
console.log(myFunction('Hello')); // Hello, world!
console.log(myFunction('Hello', 'John')); // Hello, John!
There’s an alternative way to declare a JavaScript function with an optional parameter, and that’s by using the logical OR
operator (||) in the function’s definition. This operator will return the first truthy value, or the last value if both are falsy.
Here’s what that approach looks like:
// Declare function
function myFunction(param1, param2) {
param2 = param2 || 'world';
console.log(param1 + ',' + param2 + '!')
}
// Call function
console.log(myFunction('Hello')); // Hello, world!
console.log(myFunction('Hello', 'John')); // Hello, John!
Using a Conditional Statement
The old-school way to declare a function with an optional parameter is by using a conditional statement:
function myFunction(param1, param2) {
if(param2) {
// The code to execute when the function is called with the parameter
console.log(param1 + ', ' + param2 + '!')
} else {
// The code to execute when the function is called without the parameter
console.log(param1 + ', world!');
}
}
myFunction('Hello'); // Hello, world!
myFunction('Hello', 'John') // Hello, John!
The example statement above checks if param2 is a truthy
, and then branches out your code This approach is fine, but it’s less performant than the two other methods we’ve already gone through.
In Summary
As a general rule, there are two methods for creating a JavaScript function with an optional parameter. One involves assigning a default value to the parameter, and the other, implementing a conditional statement to check if it’s a truthy or not.