Question
JavaScript Default Parameters: Set Optional Function Argument Values
Question
I want a JavaScript function to support optional arguments with default values. The default should be used when an argument is not provided, and ignored when a value is passed.
In Ruby, this can be written like this:
def read_file(file, delete_after = false)
# code
end
Can JavaScript do the same thing?
function readFile(file, deleteAfter = false) {
// code
}
Short Answer
By the end of this page, you will understand how default parameters work in JavaScript, when they are used, and how they differ from older ways of setting fallback values. You will also see practical examples, common mistakes, and how this pattern appears in real codebases.
Concept
JavaScript supports default parameters, which let you assign a fallback value to a function parameter directly in the function definition.
function readFile(file, deleteAfter = false) {
// code
}
In this example:
fileis a normal required parameter.deleteAfteris optional.- If the caller does not provide
deleteAfter, JavaScript usesfalse.
This matters because functions often need:
- required inputs for essential work
- optional inputs for customization
Default parameters make that behavior clear and readable. They also avoid extra setup code inside the function.
Before default parameters were added to JavaScript, developers often used patterns like this:
function readFile(file, deleteAfter) {
deleteAfter = deleteAfter || false;
}
That older approach can be misleading because it treats some valid values, such as 0, "", or , as if they were missing. Default parameters are safer because they only apply when the argument is .
Mental Model
Think of a function parameter like a form field with a pre-filled value.
- If the user leaves the field blank, the pre-filled value stays.
- If the user types something, that new value is used instead.
Default parameters work the same way:
- no value passed -> use the default
- value passed -> use the passed value
A key detail: in JavaScript, the default is used when the argument is undefined.
So this:
readFile("notes.txt");
uses the default.
And this:
readFile("notes.txt", true);
uses true instead of the default.
Syntax and Examples
The basic syntax is:
function functionName(parameter = defaultValue) {
// code
}
Example 1: Simple default value
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet();
greet("Ava");
Output:
Hello, Guest
Hello, Ava
If no argument is passed, name becomes "Guest".
Example 2: Multiple parameters
function createUser(username, isAdmin = false, theme = "light") {
return {
username,
isAdmin,
theme
};
}
.(());
.((, , ));
Step by Step Execution
Consider this example:
function multiply(number, factor = 2) {
return number * factor;
}
console.log(multiply(5));
console.log(multiply(5, 3));
Step-by-step
Call 1
multiply(5)
numberreceives5factoris not provided- Because
factorisundefined, JavaScript uses the default value2 - The function returns
5 * 2 - Result:
10
Call 2
Real World Use Cases
Default parameters are common in real programs whenever a function has sensible fallback behavior.
1. API request helpers
function fetchUsers(limit = 10, includeInactive = false) {
// build request
}
Useful when most requests use standard settings.
2. UI components
function createButton(label, type = "primary") {
// render button
}
A component can have a default style unless another one is provided.
3. Logging utilities
function log(message, level = "info") {
console.log(`[${level}] ${message}`);
}
Most logs may be info, but some can be warn or error.
4. File or data processing
Real Codebase Usage
In real projects, default parameters are often combined with patterns that keep functions predictable and easy to use.
Guard clauses
Developers often use defaults together with early validation.
function saveUser(user, shouldValidate = true) {
if (!user) {
throw new Error("User is required");
}
if (shouldValidate && !user.name) {
throw new Error("Name is required");
}
// save user
}
Configuration objects
When a function has many optional settings, teams often use an options object.
function connect(url, options = {}) {
const { timeout = 5000, retries = 3 } = options;
return { url, timeout, retries };
}
This scales better than many positional parameters.
Error handling defaults
function parseJson() {
{
.(text);
} {
fallbackValue;
}
}
Common Mistakes
1. Confusing undefined with null
Default parameters apply only when the argument is undefined.
function greet(name = "Guest") {
console.log(name);
}
greet(null); // prints null
If you want null to also use a fallback, handle that manually.
function greet(name = "Guest") {
if (name === null) {
name = "Guest";
}
console.log(name);
}
2. Using || instead of true default parameters
Broken approach:
function setVolume(volume) {
volume = volume || 50;
volume;
}
.(());
Comparisons
| Approach | Example | When it works well | Main downside |
|---|---|---|---|
| Default parameter | function f(x = 10) {} | Modern JavaScript, clear optional values | Requires modern JS support |
| Inside-function check | if (x === undefined) x = 10; | Explicit and compatible with older style | More verbose |
| Logical OR fallback | `x = x | 10;` | |
| Nullish coalescing inside function | x = x ?? 10; | Good when null and undefined should both fallback | Not the same behavior as default parameters |
Default parameters vs ||
Cheat Sheet
Basic syntax
function greet(name = "Guest") {
console.log(name);
}
Key rule
Default parameters are used only when the argument is:
undefined
Examples
greet(); // "Guest"
greet(undefined); // "Guest"
greet("Sam"); // "Sam"
greet(null); // null
Old alternative
function greet(name) {
if (name === undefined) {
name = "Guest";
}
}
Avoid this when falsy values are valid
name = name || ;
FAQ
Does JavaScript support default parameter values?
Yes. Modern JavaScript allows you to assign default values directly in the function parameter list.
When is a JavaScript default parameter used?
It is used when the argument is undefined, including when no argument is passed.
Does null trigger a default parameter in JavaScript?
No. If you pass null, JavaScript uses null, not the default value.
What is the difference between default parameters and ||?
Default parameters only replace undefined. || replaces any falsy value, such as 0, false, or "".
Can I use one parameter to build the default for another?
Yes. A later parameter can use an earlier one in its default value.
function greet(name, message = `Hello, ${name}`) {
console.log(message);
}
Mini Project
Description
Build a small utility function for formatting user notifications. In real applications, many functions need optional settings such as message type, prefix text, or whether to include a timestamp. This project helps you practice default parameters in a practical way.
Goal
Create a function that formats notifications using sensible default values when optional arguments are not provided.
Requirements
- Create a function named
formatNotification. - The function must accept a required message argument.
- Add an optional
typeparameter that defaults to"info". - Add an optional
includeTimestampparameter that defaults tofalse. - Return a formatted string based on the provided or default values.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.